Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "let" keyword to define multiple variables in Haskell

Tags:

let

haskell

I've the below code snippet in Haskell to implement the quicksort algorithm.

quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) =
let smaller = quicksort [a | a <- xs, a <= x]
    bigger  = quicksort [a | a <- xs, a > x]
in smaller ++ [x] ++ bigger

However, GHCi rejects the program telling me that line 5 has a syntax error. But I've checked the Haskell syntax for the "let" keyword and it seems OK.

Is there anyone who can help me with this problem? Thanks a lot.

like image 405
Lyndon Avatar asked Aug 05 '16 15:08

Lyndon


People also ask

Where vs let in Haskell?

It is important to know that let ... in ... is an expression, that is, it can be written wherever expressions are allowed. In contrast, where is bound to a surrounding syntactic construct, like the pattern matching line of a function definition.

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.

What does ++ mean in Haskell?

The ++ operator is the list concatenation operator which takes two lists as operands and "combine" them into a single list.


Video Answer


2 Answers

You need to indent the let expression, since it is a continuation of the previous line.

quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) =
  let smaller = quicksort [a | a <- xs, a <= x]
      bigger  = quicksort [a | a <- xs, a > x]
  in smaller ++ [x] ++ bigger
like image 176
chepner Avatar answered Oct 17 '22 14:10

chepner


Another way to do this You can write it in one line using braces and semicolons { ; ; ; }:

quicksort (x:xs) = let {smaller = quicksort [a | a <- xs, a <= x]; bigger = quicksort [a | a <- xs, a > x]} in smaller ++ [x] ++ bigger

like image 28
Николай Николай Avatar answered Oct 17 '22 15:10

Николай Николай