Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Haskell have variables?

I've frequently heard claims that Haskell doesn't have variables; in particular, this answer claims that it doesn't, and it was upvoted at least nine times and accepted.

So does it have variables or not, and why?

This question also appears to apply ML, F#, OCaml, Erlang, Oz, Lava, and all SSA intermediate languages.

like image 830
cjs Avatar asked Jun 14 '09 16:06

cjs


People also ask

Can you assign variables in Haskell?

We first note that variables in Haskell can only be assigned once, unlike in many imperative programming languages, where a variable can be overwritten with different values arbitrarily many times.

Does Haskell have global variables?

So, in particular, all those tasks which you use global variables for in C, can be achieved in haskell, but which solution depends what you are trying to do: If you have some globals which are constant, then just define them at the top level.

Are variables in Haskell immutable?

Expressions in Haskell are immutable. They cannot change after they are evaluated. Immutability makes refactoring super easy and code much easier to reason about. To “change” an object, most data structures provide methods taking the old object and creating a new copy.

How do you assign a value to a variable in Haskell?

You declare a variable; Haskell doesn't allow uninitialized variables, so you are required to supply a value in the declaration; There's no mutation, so the value given in the declaration will be the only value for that variable throughout its scope.


1 Answers

Haskell has immutable variables (variables in the math sense) by default:

 foo x y = x + y * 2 

By default variables are not mutable cells.

Haskell also has mutable cells though, but you enable them explicitly:

 > import Data.IORef (newIORef, readIORef, writeIORef)  > v <- newIORef 0  > readIORef v  0   > writeIORef v 7  > readIORef v  7 

So, YES Haskell has true variables. But it does not use mutable variables by default.

like image 101
Don Stewart Avatar answered Oct 02 '22 20:10

Don Stewart