WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Haskell · Basic · question 4 of 100

How are variables declared and assigned in Haskell?

📕 Buy this interview preparation book: 100 Haskell questions & answers — PDF + EPUB for $5

In Haskell, variables are not declared and assigned in the traditional sense found in imperative languages. Instead, Haskell uses a concept called "binding" to give names to values.

Variable bindings are created with a simple equal sign "`=‘". Haskell evaluates expressions on the right-hand side and binds them to the variable names on the left-hand side. Once a variable is bound to a value, it cannot be changed, meaning that variables in Haskell are immutable.

Here’s a simple example to illustrate variable binding in Haskell:

x :: Int
x = 5

y :: Int
y = x * 2

Here, variables ‘x‘ and ‘y‘ are declared with their specific types (‘Int‘), using the ‘::‘ type signature operator. Then, ‘x‘ is bound to the value 5, and ‘y‘ is bound to the value of ‘x * 2‘, i.e., 10. Since variables are immutable, we cannot change the value of ‘x‘ or ‘y‘ later in the program.

For functions, variables are bound via pattern matching. When defining a function, we specify the variable names in the function arguments, and Haskell binds the actual values passed to the function when it’s called. Here’s an example:

add :: Int -> Int -> Int
add a b = a + b

In this case, the ‘add‘ function accepts two arguments of type ‘Int‘, represented by variables ‘a‘ and ‘b‘. When the function is called, Haskell binds the values passed to these variables, and the expression on the right-hand side (‘a + b‘) is evaluated.

Keep in mind that, in Haskell, expressions are evaluated lazily. This means that a variable’s value is only computed when it’s needed. For example:

z :: Int
z = x + y

The value of ‘z‘ will only be determined when the program actually requires it for some operation.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Haskell interview — then scores it.
📞 Practice Haskell — free 15 min
📕 Buy this interview preparation book: 100 Haskell questions & answers — PDF + EPUB for $5

All 100 Haskell questions · All topics