0

这是我必须制作回文函数的代码。在我用来制作回文之前,我已经创建了 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 
4

3 回答 3

1

您应该使用List.rev标准函数来反转列表。Ocaml 是一个免费软件,你应该看看它的实现(文件stdlib/list.ml

于 2012-10-12T05:42:15.073 回答
1

尝试用简单的英语(而不是代码)解释你在写作时想要达到的目标

if c :: d 
  else false

另外,请注意

if foo = bar then true else false

应该简化为

foo = bar
于 2012-10-12T05:52:44.670 回答
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)
于 2012-10-12T17:47:02.057 回答