Skip to main content

The Standard Prelude

Starting the interpreter is done by ghci Haskell comes with a large number of standard library functions. Also provides many useful functions on lists

Select first number of list:

head [1,2,3,4]
1

Remove the first element:

tail [1,2,3,4]
[2,3,4,5]

Select the nth element of a list: ! is known as a bang

[1,2,3,4,5] !! 2
3

Select the first n elements of a list:

take 3 [1,2,3,4,5]
[1,2,3]

Remove the first n elements:

drop 3 [1,2,3,4,5]
[4,5]

Calculate the length of a list:

length [1,2,3,4,5]
5

Calculate the sum of a list of numbers. Sum is 0 if list is empty. 0 is identity for addition:

sum [1,2,3,4,5]
15

Calculate the product of a list. Would return 1 if the list is empty. 1 is identity for multiplication:

product [1,2,3,4,5]
120

Append two lists:

[1,2,3] ++ [4,5]
[1,2,3,4,5]

Reverse a list:

reverse [1,2,3,4,5]
[5,4,3,2,1]

Function Application

In maths function application is denoted using parentheses and multiplication of denoted using juxtaposition or space. In maths it would look like: f(a,b) + c d In haskell is denoted using space and multiplication denoted using : `f a b + cdFunction application is assume to have higher priority than all other operatorsf a + bmeans (haskell does this)(f a) + brather thanf(a+b)`

Haskell scripts

Can define your own functions New functions are defined within a script, a text file comprising a sequence of definitions. Normally have .hs

``

Is a infix operator. x f y is just syntactic sugar for f x y Have to reload :reload once files been saved to ghci no there's a change

Naming requirements

Function and argument names must begin with a lower-case letter By convention, list arguments usually have an s suffix on their name

The layout Rule

In a sequence of definitions, each definition must begin in precisely the same column Means you don't have to do explicitly grouping, using {}, can instead use indentation/columns for definitions