Variable Assignment in Haskell

Subscribe to my newsletter and never miss my upcoming articles

In Haskell when you define a variable you cannot change that variable values unlike Imperative languages.

AssignmentAssignment

For example In C we can define:

int value = 0 
value = 1 // We can update the value In this case to 1

The above assignment is legal in C-Style Imperative Programming languages.

While in Haskell if you define a variable and bind a value. In the scope the variable is declared it will remain unchanged

For example let take this snippet

Prelude> inc x = x + 1
Prelude> xinc x = inc x 
Prelude> inc 1
2
Prelude> xinc 1
2
Prelude> inc x = x + 2
Prelude> inc 1
3
Prelude> xinc 1
2

In the above snippets of Haskell code, we define two functions inc, and xinc. when we passed the value 1 to the inc it returns 2. When we pass the value 1 to xinc it return 2 and then later on we updated the definition of inc passed the value 1 it returns 3. while xinc still return the value 2 when passed 1 because the scope of the inc function is different from the scope of the function inc defined later on, in the repl.

So from above, we concluded that in Haskell we cannot mutate variables.

Resources

  1. https://stackoverflow.com/questions/35198897/does-mean-assigning-a-variable-in-haskell

  2. http://learnyouahaskell.com/

  3. https://en.wikipedia.org/wiki/Scope_(computer_science))