Defining Variables Inside a Haskell Function

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. Let's say I have a 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?

+6
source share
2 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 aesthetic rather than technical. More precisely, where can only be bound to definitions, while let ... in ... can be used wherever an expression is allowed. Both where and let introduce blocks, which makes several internal variables convenient in both cases.

+19
source

Apart from technical correctness, the answer is "sort of."

I think it's best to think of a variable as a function of null arguments evaluating 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 
+1
source

Source: https://habr.com/ru/post/920748/


All Articles