这是我必须制作回文功能的代码。我之前已经创建了listReverse和explode函数来制作回文。有人可以帮我修复回文功能吗?
let rec listReverse l = match l with
|[] -> []
|head :: tail -> (listReverse tail) @ [head]
(* explode : string -> char list
* (explode s) is the list of characters in the string s in the order in
* which they appear
* e.g. (explode "Hello") is ['H';'e';'l';'l';'o']
*)
let explode s =
let rec _exp i =
if i >= String.length s then [] else (s.[i])::(_exp (i+1)) in
_exp 0
let rec palindrome w =
let a = explode w in
let b = listReverse a in
if c :: d
else false
答案 0 :(得分:1)
您应该使用List.rev标准功能来反转列表。 Ocaml是一个免费软件,你应该看看它的实现(文件stdlib/list.ml
)
答案 1 :(得分:1)
尝试用简单的英语(而不是代码)解释你在写作时想要达到的目标
if c :: d
else false
另外,请注意
if foo = bar then true else false
应该简化为
foo = bar
答案 2 :(得分:0)
您可以将if语句替换为:
(* tells wheter its a palindrome or not; most is (List.length a)/2*)
let rec same l1 l2 cur most =
match l1, l2 with
| h1::t1, h2::t2 when h1 = h2 ->
if cur < most then same t1 t2 (cur+1) most
else true
| _ -> false in
same a b 0 ((List.length a)/2)