Bobby Tables
Bobby Tables

Reputation: 1184

Defining variables inside a function 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?

Upvotes: 18

Views: 31532

Answers (2)

Daniel Wagner
Daniel Wagner

Reputation: 153332

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.

Upvotes: 33

Paul Nathan
Paul Nathan

Reputation: 40319

Disregarding technical correctness, the answer is "sort of".

I think it's better to think of a variable as a function of zero arguments evaluating to a given value.

module Main where
import System.IO

foo :: Integer -> Integer
foo a =
  b where
    b = a * 2

main = do
  putStrLn $ show $ foo 10

Upvotes: 3

Related Questions