tags:

views:

810

answers:

2

What is wrong with rs definition in first where section?

palindrome :: [a] -> [a]

palindrome xs = con xs rs
    where con a b = rev (rev a []) b
        rs = rev xs                        -- here
        where rev [] rs = rs
            rev (x:xs) rs = rev xs (x:rs)

I'm just learning haskell but its syntax rules confuse me. Error message is

[1 of 1] Compiling Main             ( pelindrome.hs, interpreted )

pelindrome.hs:5:8: parse error on input `rs'
+6  A: 

Your indentation was wrong and i think you can only have one where in there (i could be very well wrong. I'm not a haskell guy). There was also a argument missing for the call to rev (an empty list):

palindrome :: [a] -> [a]
palindrome xs = con xs rs
    where con a b = rev (rev a []) b
          rs = rev xs []                       -- here
          rev [] rs = rs
          rev (x:xs) rs = rev xs (x:rs)

main = print (palindrome "hello")

Prints out:

"helloolleh"

I'm going to try to understand it now. Anyway, have fun!

Edit: Makes perfect sense to me now. I think that's the right version. For Haskell indentation rules, read Haskell Indentation

Johannes Schaub - litb
You are right, rs must start in same column as con in previous line. It is weird rule.
Hynek -Pichi- Vychodil
Not weird: same syntactic level -> same indentation
Svante
you can use braces to "break" out that rule
Johannes Schaub - litb
A: 

@litb: You can rewrite con in way

palindrome :: [a] -> [a]
palindrome xs = con xs rs
    where con [] b = b
          con (x:xs) b = x:con xs b
          rs = rev xs []                       -- here
          rev [] rs = rs
          rev (x:xs) rs = rev xs (x:rs)

which is how ++ is implemented in prelude. My previous version is way how to write it in non lazy functional or logical languages in tail call fashion (e.g. Erlang).

Hynek -Pichi- Vychodil