我想要像
string(2^n)
那样编码。
例如。
let string2 s =
match s with
" " -> " "
| _ -> s^s;;
但是,
let rec string128 s =
match s with
" " -> " "
| _ -> string128 s^s ;;
有溢出。如何仅使用递归函数进行编码? 我不想使用其他参数。就像`n -> n-1'
如果我将 'a' 放入 string128 中,然后重复 'a' 128 次。
我不确定为什么你不想使用额外的参数,但你可以使用字符串的长度作为终止条件。由于尚不清楚您要如何处理具有多个字符的初始字符串,因此这里有两种可能的版本:
let rec string128 s =
if String.length s >= 128 then s
else string128 (s^s);;
let string128bis s =
let orig_length = String.length s in
let rec aux s =
if String.length s >= 128 * orig_length then s
else aux (s^s)
in
aux s;;
string128
将连接字符串,直到结果至少为 128 个字符宽。 string128bis
将等待结果字符串比原始输入长 128 倍。 string128 "a"
和string128bis a
都将返回128a
,但string128 "abcd"
将返回重复abcd
的128个字符的字符串,而string128bis "abcd"
将返回512个字符长。