Haskell Multi-line Lambdas

2019-07-07 17:45发布

问题:

I am learning Haskell from learnyouahaskell.com and there is an example such that:

search :: (Eq a) => [a] -> [a] -> Bool  
search needle haystack =   
    let nlen = length needle  
    in  foldl (\acc x -
> if take nlen x == needle then True else acc) False (tails haystack) 

But when tried this code with GHC, it gives me

error: parse error on input ‘-’

But it works when it is like this:

search :: (Eq a) => [a] -> [a] -> Bool  
search needle haystack =   
    let nlen = length needle  
    in  foldl (\acc x -> if take nlen x == needle then True else acc) False (tails haystack) 

Is there a feature of Haskell that allows multi-line lambdas or is that something I am missing?

回答1:

Don't break the ->

Just do:

search :: (Eq a) => [a] -> [a] -> Bool  
search needle haystack =   
   let nlen = length needle  
   in  foldl (\acc x ->
if take nlen x == needle then True else acc) False (tails haystack) 

or

search :: (Eq a) => [a] -> [a] -> Bool  
search needle haystack =   
   let nlen = length needle  
   in  foldl (\acc x 
-> if take nlen x == needle then True else acc) False (tails haystack)