Haskell

( Part deux )

Open

ghc.io

Usage

:t <something>

Show the type of <something>

eg :t False

:i <something>

Show info of <something>

eg :t Bool

To define stuff (in ghci )

let count = 1
let add x y = x + y

Types

:t 'c'
:t False
:t 4 == 5 
:t "meh."  
:t (1, '3')

Hint

Types are always uppercase

['L', 'I', 'S', 'T']

( list )

Lists are homogenus

Can only store elements of the same type

Example

let lotto = [1,5,6,7]
[1,2,3,4] ++ [9,10,11,12] 
"hello" ++ " " ++ "world"  

Operations on lists

'A' : " FAT CAT" 
1 : [2,3,4]
[12,11,10,9] !! 3
"Good Day" !! 3

Lists can also contain lists. 

They can also contain lists that contain lists that contain lists …

[[1,2,3], [9,8,7]]

Lists can be compared 

if the stuff they contain can be compared

[3,2,1] > [2,1,0]  
[3,4,2] > [3,4]  
[3,4,2] == [3,4,2]  

Some
Basic
Functions

head [5,4,3,2,1] 
tail [5,4,3,2,1]  
last [5,4,3,2,1]  
init [5,4,3,2,1]  
length [5,4,3,2,1]  
reverse [5,4,3,2,1]  
take 3 [5,4,3,2,1]  
drop 3 [8,4,2,1,5,6]  
minimum [8,4,2,1,5,6]  
10 `elem` [3,4,5,6]  

MOAR

4 `elem` [3,4,5,6]  
maximum [8,4,2,1,5,6]  
sum [8,4,2,1,5,6]  
product [8,4,2,1,5,6]  

Ranges

[1..20]  
['a'..'z']  
['K'..'Z']  

MOAR

[2,4..20]  
['a'..'z']  
['K'..'Z']  

Handy Functions

take 10 (cycle [1,2,3])  
take 10 (repeat 5)  
replicate 3 10

List comprehensions

[x*2 | x <- [1..10]]  
[x*2 | x <- [1..10], x*2 >= 12] 
[x*2 | x <- [1..10], x*2 >= 12] 

List comprehensions

[ x*y | x <- [2,5,10], y <- [8,10,11]]  
[ x*y | x <- [2,5,10], y <- [8,10,11], x*y > 50]  
removeNonUppercase st = [ c | c <- st, c `elem` ['A'..'Z']]   
removeNonUppercase "Hahaha! Ahahaha!"  
"HA"  

Tuples

fst (8,11)  
snd (8,11)  
zip [1,2,3,4,5] [5,5,5,5,5]  
[(1,5),(2,5),(3,5),(4,5),(5,5)]  

Functions

have types

Algebraic

data types

How to

Roll Our
Own

the data keyword

data Bool = True | False
data Bool = True | False

Name of our new data type

Value Constructors

Can be read as logical or

The type Bool can have a value of either True or False

Example

shapes

data Shape = Circle Float | Square Float | Rectangle Float Float

You can optionally add a type after the value constructor.

Value constructors

Are actually functions

They also have type signatures

Haskell

By ..

Haskell

  • 468
Loading comments...

More from ..