← All writing

Haskell

Haskell learning notes covering toolchain setup, expressions, functions, pattern matching, guards and lists. Explores immutability, type inference, polymorphism and the Maybe and Either types.

Haskell

0 ghcup

GHCup is like your system's package manager (apt) but specifically for the Haskell compiler and its associated binaries (like the linker and language server).

Cabal/Stack are what you will use to download libraries from Hackage (Haskell's version of PyPI).

check this install list

Code
ghcup list

Code
   Tool  Version     Tags                      Notes     
✗  ghc   9.6.4       base-4.18.2.0                       
✗  ghc   9.6.5       base-4.18.2.1                       
✗  ghc   9.6.6       base-4.18.2.1                       
✔✔ ghc   9.6.7       recommended,base-4.18.3.0           
✗  ghc   9.8.1       base-4.19.0.0             2023-10-09
✗  ghc   9.8.2       base-4.19.1.0             2024-02-23
✗  ghc   9.8.4       base-4.19.2.0             2024-11-27
✗  ghc   9.10.1      base-4.20.0.0                       
✗  ghc   9.10.2      base-4.20.1.0                       
✗  ghc   9.10.3      base-4.20.1.0                       
✗  ghc   9.12.1      base-4.21.0.0             2024-12-15
✗  ghc   9.12.2      base-4.21.0.0             2025-03-12
✓  ghc   9.14.1      latest,base-4.22.0.0      2025-12-18          
✗  cabal 3.14.1.0                                        
✗  cabal 3.14.1.1                                        
✗  cabal 3.14.1.1-p1                                     
✔✔ cabal 3.14.2.0    recommended                         
✗  cabal 3.16.0.0                                        
✗  cabal 3.16.1.0    latest                              
✗  hls   2.11.0.0                                        
✗  hls   2.12.0.0                                        
✓  hls   2.13.0.0    latest,recommended                  
✗  stack 3.3.1                                           
✗  stack 3.5.1                                           
✔✔ stack 3.7.1       recommended                         
✗  stack 3.9.1       latest     

✗ (Cross): The tool is not installed.

✓ (One Tick): The tool is installed, but it is not the active version currently linked to your command line. For example, you have ghc 9.14.1 installed, but it isn't your default.

✔✔ (Two Ticks): The tool is installed and active. This version is what runs when you type ghc, cabal, or stack in your terminal.

1 Basic

check a type

sh
ghci> :t "saber"
"saber" :: String

Define variable, funciton

Haskell have type inference

haskell

x = 1 :: Int

-- type inference

z = 1

y :: String
y = saber

polynomial :: Double -> Double
polynomial x = x^2 - x - 1

Arithmetic

In Haskell there are two division functions, the / operator and the div function. The div function does integer division:

Code
ghci> 7 `div` 2
3

The / operator performs the usual division:

Code
ghci> 7.0 / 2.0
3.5

However, you can only use div on whole number types like Int and Integer, and you can only use / on decimal types like Double.

if

haskell
price = if product == "milk" then 1 else 2

In Haskell, if is an expression. It has a value. It selects between two other expressions.Because Haskell’s if returns a value, you always need an else! (It is like exprssion ? value1 : value2 in C/C++)

not equal

One oddity of Haskell is that the not-equals operator is written /= instead of the usual !=

haskell
ghci> 2 /= 3
True

Local Definitions

Haskell has two different ways for creating local definitions: let...in and where.

where adds local definitions to a definition:

haskell
circleArea :: Double -> Double
circleArea r = pi * rsquare
    where pi = 3.1415926
          rsquare = r * r

let...in is an expression:

haskell
circleArea r = let pi = 3.1415926
                   rsquare = r * r
               in pi * rsquare

Pattern Matching

A definition (of a function) can consist of multiple equations. The equations are matched in order against the arguments until a suitable one is found. This is called pattern matching. Pattern matching in Haskell is very powerful.

Guards

haskell
f x y z
  | condition1 = something
  | condition2 = other
  | otherwise  = somethingother

A condition can be any expression of type Bool. The first condition that evaluates to True is chosen. The word otherwise is just an alias for True. It is used to mark the default case.

Lists

haskell
[True,True,False] :: [Bool]
["Moi","Hei"] :: [String]
[] :: [a]                   -- more about this later
[[1,2],[3,4]] :: [[Int]]    -- a list of lists
[1..7] :: [Int]             -- range syntax, value [1,2,3,4,5,6,7]

List Operations

haskell
head :: [a] -> a            -- returns the first element
last :: [a] -> a            -- returns the last element
tail :: [a] -> [a]          -- returns everything except the first element
init :: [a] -> [a]          -- returns everything except the last element
take :: Int -> [a] -> [a]   -- returns the n first elements
drop :: Int -> [a] -> [a]   -- returns everything except the n first elements
(++) :: [a] -> [a] -> [a]   -- lists are concatenated with the ++ operator
(!!) :: [a] -> Int -> a     -- lists are indexed with the !! operator
reverse :: [a] -> [a]       -- reverse a list
null :: [a] -> Bool         -- is this list empty?
length :: [a] -> Int        -- the length of a list

A Word About Immutability!!!

Because Haskell is pure, it also means that functions can’t mutate (change) their inputs. Mutation is a side effect, and Haskell functions are only allowed output via their return value. This means that Haskell list functions always return a new list!!!!

A Word About Type Inference and Polymorphism

So what does a type like head :: [a] -> a mean? It means given a list that contains elements of any type a, the return value will be of the same type a.

In this type, a is a type variable. Type variables are types that start with a small letter, e.g. a, b, thisIsATypeVariable. A type variable means a type that is not yet known, or in other words a type that could be anything. Type variables can turn into concrete types (e.g. Bool) by the process of type inference (also called unification).


The Maybe Type

Sometimes an operation doesn’t have a valid return value (E.g. division by zero.). We have a couple of options in this situation. We can use an error value, like -1. This is a bit ugly, not always possible. We can throw an exception. This is impure. In some other languages we would return a special null value that exists in (almost) all types. However Haskell does not have a null.

The solution Haskell offers us instead is to change our return type to a Maybe type. This is pure, safe and neat. The type Maybe a has two constructors: Nothing and Just. Nothing is just a constant, but Just takes a parameter. More concretely:

TypeValues
Maybe BoolNothing, Just False, Just True
Maybe IntNothing, Just 0, Just 1, …
Maybe [Int]Nothing, Just [], Just [1,1337], …

You can think of Maybe a as being a bit like [a] except there can only be 0 or 1 elements, not more. Alternatively, you can think of Maybe a introducing a null value to the type a. If you’re familiar with Java, Maybe Integer is the Haskell equivalent of Java’s Optional<Integer>.

haskell
-- Multiply an Int with a Maybe Int. Nothing is treated as no multiplication at all.
perhapsMultiply :: Int -> Maybe Int -> Int
perhapsMultiply i Nothing = i
perhapsMultiply i (Just j) = i*j   -- Note how j denotes the value inside the Just

The Either type

Sometimes it would be nice if you could add an error message or something to Nothing. That’s why we have the Either type. The Either type takes two type arguments. The type Either a b has two constructors: Left and Right. Both take an argument, Left an argument of type a and Right an argument of type b.

TypeValues
Either Int BoolLeft 0, Left 1, Right False, Right True, …
Either String [Int]Left "asdf", Right [0,1,2], …
Either Integer IntegerLeft 0, Right 0, Left 1, Right 1, …

Here’s a simple example: a readInt function that only knows a couple of numbers and returns a descriptive error for the rest. Note the Haskell convention of using Left for errors and Right for success.

haskell
readInt :: String -> Either String Int
readInt "0" = Right 0
readInt "1" = Right 1
readInt s = Left ("Unsupported string: " ++ s)

Sidenote: the constructors of Either are called Left and Right because they refer to the left and right type arguments of Either. Note how in Either a b, a is the left argument and b is the right argument. Thus Left contains a value of type a and likewise Right of type b. The convention of using Right for success is probably simply because right also means correct. No offense is intended to left-handed people.

Indentation

The previous examples have been fancily indented. In Haskell indentation matters, a bit like in Python. The complete set of rules for indentation is hard to describe, but you should get along fine with these rules of thumb:

  1. Things that are grouped together start from the same column
  2. If an expression (or equation) has to be split on to many lines, increase indentation
haskell
i x = let y = x+x+x+x+x+x in div y 5

-- let and in are grouped together, an expression is split
j x = let y = x+x+x
              +x+x+x
      in div y 5

-- the definitions of a and b are grouped together
k = a + b
  where a = 1
        b = 1

l = a + b
  where
    a = 1
    b = 1

Catamorphic

← Back to ArchiveBack to top ↑

Comments

No approved comments yet.

Your display name and plain-text comment become public only after owner approval. No account or email is required.