7

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. The error message is

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

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

2 Answers 2

14

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

Sign up to request clarification or add additional context in comments.

3 Comments

You are right, rs must start in same column as con in previous line. It is weird rule.
Not weird: same syntactic level -> same indentation
you can use braces to "break" out that rule
0

@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).

1 Comment

I thought (++) was defined as (++) = flip $ foldr (:) - that's how I would've written it anyways.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.