Föreläsning 2

Second lecture

Ludde127 2023-03-22
L

Infinite lists

Computing primes with Erathones sieve:

sieve (n:ns) =

n : sieve [x | x <- ns, x 'mod' n > 0]

Cumsum

runningSums xs = theSolution
	where
	    theSolution = zipWith (+) xs (0:theSolution)

Haskell

  • Haskell is strongly and statically typed
  • Type declarations optional
  • Type checking uses type inferencing
  • Enforced convention:
    • Type names: begin with an uppercase letter
    • variable/expression names; begin with a lowercase letter.

Parentheses avoided:

f a b

is to be read ((f a) b)

and is different from

f (a, b)

f (a b)

Lambda expression

incAll = map(\i->i+1)

Pattern-based definitions

count 1 = "one"

count 2 = "two"

count _ = "many"

Guards

oddOrEven :: Int -> String

oddOrEven i

| odd i = "odd"

| even i = "even"

| otherwise = "strange"

Indentation

  • indentation denotes continuations
  • some keywords can be used to start new indentation blocks

Polymorphic types

The type of (.) // <-- Composition

(f.g) x = f (g x)

is

(b -> c) -> (a -> b) -> a -> c // Composition

Type variables begin with a lowercase letter.

Tuples

Fixed number of elements, may be of different types

(4, "4") :: (Int, String)

Lists

Arbitrary number of elements of the same type

[1, 2, 3 ,4] :: [Int]

[2..] :: [Int] // All the numbers over 2

Functions on lists

length1 :: [a] -> Int

length1 [] = 0

length1 (x:xs) = 1 (length1 xs)

some standard list functions

filter

filter even [1..]

map:

map doublePlusOne [1..3]

fold (foldr, foldl):

sum = foldr (+) 0

zip

List comprehension

allIntPairs = [(i,j) | i<-[0..], j<-[0..i]]

eExp x = runningSums[ (x^i) / (fac i) | i <- [0..]]

Infinite lists

ones1 = 1:ones1

ones2 = [1, 1...]

sieve1 (n:ns) = n: sieve1 (filter (\x -> x 'mod' n > 0)

type synonyms

type Name = String

Enumerated types

data Color =

Red | Green | Blue | Yellow | Black | White

Enumerated types generalized!

data Price =

Euro Int Int | Dollar Int Int

Pattern matching rev

complement:: Color -> Color

complement red = Green

complement Green = Red

complement >Blue = Yellow

complement _ = Blue

The pattern cases correspond to alternative construction functions of the data types.

Recursive type definitions

There's not functions that can not be defined as recursions in theory lolz.

data IntTree

= IntEmpty| IntNode Int IntTree IntTree

or a polymorphic version

data Tree a = Empty | Node a (Tree a) (Tree a)

Qualified types

the type of:

elem x xs = any (==x) xs

is (Eq a) => a -> [a] -> Bool

The abstract datatype IO

putChar :: Char -> IO ()

getChar :: IO Char