Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining variables inside a function Haskell

Tags:

haskell

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?

like image 626
Bobby Tables Avatar asked Jul 17 '12 21:07

Bobby Tables


1 Answers

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.

like image 175
Daniel Wagner Avatar answered Sep 18 '22 15:09

Daniel Wagner