Archive for the ‘Haskell’ tag
Haskell: parse error on input `=’
I’ve been trying to follow the ‘Monads for Java/C++ programmers‘ post in ghci and getting the following type of error when trying out the code snippets:
Prelude> a = 3 <interactive>:1:2: parse error on input `='
I figured there must be something wrong with my installation of the compiler since I was copying and pasting the example across and having this problem. Having reinstalled that, however, I still had the same problem.
I eventually came across this blog post which points to a mailing list thread from a few years ago where pjd explains that the ‘let’ construct is required when defining a variable from ghci and wouldn’t necessarily be needed in a normal program:
pjd osfameron: about the ghci thing, you have to prefix definitions with “let”
as in: let simple x y z = x * (y + z)
pjd the reason for this is that ghci is in an implicit do block
pjd so it’s not exactly like top-level haskell
We have to use a ‘let’ in front of any variable/function definitions and then it will work as expected:
Prelude> let a = 3 3
According to Real World Haskell:
This syntax is ghci-specific
The syntax for let that ghci accepts is not the same as we would use at the “top level” of a normal Haskell program.
Haskell vs F#: Function composition
I’m reading through John Hughes’ ‘Why functional programming matters‘ paper and one thing I’ve come across which is a bit counter intuitive to me is the Haskell function composition operator.
I’ve written previously about F#’s function composition operator which is defined as follows:
let inline (>>) f g x = g(f x)
To write a function which doubled all the values in a list and then returned the odd values we’d do this:
let doubleThenOdd = List.map (fun x -> x*2) >> List.filter (fun x -> x % 2 <> 0)
Of course it’s not possible for there to be any values!
doubleThenOdd [1..5];; val it : int list = []
Based on that understanding I would expect the Haskell function composition operator (‘.’) to work in the same way:
let doubleThenOdd = map (\ x -> x*2) . filter (\ x -> (mod x 2) /= 0)
But it doesn’t!
Prelude> doubleThenOdd [1..5] [2,6,10]
In Haskell the functions are applied from right to left rather than left to right as I had expected.
The definition of ‘.’ is therefore:
(f . g) x = f (g x)
So to get what I wanted we’d need to switch around ‘map’ and ‘filter’:
let doubleThenOdd = filter (\ x -> (mod x 2) /= 0) . map (\ x -> x*2)
Prelude> doubleThenOdd [1..5] []
It’s not too difficult to follow once I worked out that it was different to what I was used to but I was very confused for a while!
Is there a reason why they implement this operator differently?