Alex Yang
Alex Yang

Reputation: 61

ocaml listReverse error

This is the code I have to make a palindrome function. I already created the listReverse and explode function before that I use to make the palindrome. Can someone help me finnish the palindrome function?

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 

Upvotes: 0

Views: 666

Answers (3)

Joseph Elcid
Joseph Elcid

Reputation: 877

You can replace your if statement with this:

 (* 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)

Upvotes: 0

jrouquie
jrouquie

Reputation: 4405

Try to explain in plain English (not code) what you are trying to achieve when you write

if c :: d 
  else false

Also, note that

if foo = bar then true else false

should be simplified to

foo = bar

Upvotes: 2

You should use the List.rev standard function to reverse lists. Ocaml being a free software, you should look at its implementation (file stdlib/list.ml)

Upvotes: 1

Related Questions