helloword
helloword

Reputation: 53

Syntax error using where or let in binding in Hashkell

I'm newie to the Haskell world recently. And still, struggle with syntax. Both methods follow have syntax errors. What could be the problem? Version 1:

rev' :: [a] -> [a]
rev' [] = []
rev' [x] = [x]
rev' (x:xs) = let revHelper acc l = 
                    | acc [] = []
                    | revHelper acc (x':l') = revHelper (x':acc) l'
              in revHelper [] (x:xs)

Version 2:

rev' :: [a] -> [a]
rev' [] = []
rev' [x] = [x]
rev' (x:xs) = revHelper [] (x:xs)
    where revHelper acc l = 
            | acc [] = []
            | revHelper acc (x':l') = revHelper (x':acc) l'

Both have the same problem:

util.hs:47:21: error: parse error on input ‘|’
   |
47 |                     | acc [] = []
   |

Can anyone help me?

I'm trying implementation a tail recursive reverse function.

Upvotes: 1

Views: 39

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476669

You are using guards the wrong way. Likely you want to implement this with:

rev' :: [a] -> [a]
rev' [] = []
rev' [x] = [x]
rev' (x:xs) = let revHelper acc [] = []
                  revHelper acc (x':l') = revHelper (x':acc) l'
              in revHelper [] (x:xs)

This however is not entirely correct: you should return the accumulator, so:

rev' :: [a] -> [a]
rev' [] = []
rev' [x] = [x]
rev' (x:xs) = let revHelper acc [] = acc
                  revHelper acc (x':l') = revHelper (x':acc) l'
              in revHelper [] (x:xs)

Furthermore it is not necessary to here define base cases for rev', you can implement this as:

rev' :: [a] -> [a]
rev' = go []
    where go acc [] = acc
          go acc (x:xs) = go (x:acc) xs

Upvotes: 2

Related Questions