I am a huge newbie to Haskell, I actually just started 10 minutes ago. I am trying to figure out how to define a variable inside a function. Lets say I have the function
foo :: Int -> Int
foo a =
b = a * 2
b
-- Yes, I know, it doesn't do anything interesting
When I run it in GHCi
I get a syntax error! How can you define a variable inside a function?
There are two ways to do this:
foo a = b where b = a * 2
foo a = let b = a * 2 in b
In most cases, the choice between them is an aesthetic rather than technical one. More precisely, where
may only be attached to definitions, whereas let ... in ...
may be used anywhere an expression is allowed. Both where
and let
introduce blocks, making multiple internal variables convenient in both cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With