2016-10-30 21:22

Page 1
examplePair::(Double,Bool)examplePair=(3.14,False)exampleTriple::(Bool,Int,String)exampleTriple=(False, 42, "Answer")exampleFunction::(Bool,Int,String)->BoolexampleFunction(b,n,s)=notb&&lengths<n

- Also collections of things
- All elements have the same type
- The number of elements can vary

- If is a type, then
**A**is the type of lists with elements of type[

**A**].**A**- For example is a list of numbers of type
[

**Integer**].**Integer**

- For example

- The values in are in either of the form
[

**A**]- , the empty list (also called
[]

*nil*) - , where
`x`**:**`xs`is of type`x`, and**A**is of type`xs`[

**A**]- is the head of the list
`x` - is the tail of the list
`xs`

- Which of these are in ?
[

**Integer**]42

**:**[]42

**:**91

**:**(2**:**[])

- The following are different ways of writing the same list
1

**:**(2**:**(3**:**[]))1

**:**2**:**3**:**[][1,2,3]

[1,2]

`++`[3][1

**..**3]

- The last example is special. It generates a sequence of values and only
works for enumeration types. Another example is .
['a'

**..**'z']

- Functions over lists can be defined by using pattern matching, e.g.
`summary`**::**[**String**]**->****String**`summary`[]**=**"Nothing"`summary`[`x`]**=**"Just "`++``x``summary`[`x`,`y`]**=**`x``++`" and "`++``y``summary`**_****=**"Several things"

- The last equation uses the wild card pattern
**_**

-- doubles [3,6,10] = [6,12,20]doubles::[Integer]->[Integer]doubles[]=(...)doubles(x:xs)=(...)

- Primitive recursion is the mosts common form when defining list functions
from scratch
-- doubles [3,6,10] = [6,12,20]

`doubles`**::**[**Integer**]**->**[**Integer**]`doubles`[]**=**[]`doubles`(`x`**:**`xs`)**=**2`*``x`**:**`doubles``xs`

- But this is a common pattern and there is a more general function that captures it.

-- map f [x1,x2,...,xn] = [f x1,f x2,...,f cn]mapf[]=...mapf(x:xs)=...

-- map f [x1,x2,...,xn] = [f x1,f x2,...,f cn]

`map``f`[]**=**[]`map``f`(`x`**:**`xs`)**=**`f``x`**:**`map``f``xs`- Note: map is a predefined function

- Selects elements that have a certain property:
- Example:
`filter``even`[1**..**9]`==`[2,4,6,8]

- Example:
`filter`**::**(`a`**->****Bool**)**->**[`a`]**->**[`a`]`filter``p`[]**=**[]`filter``p`(`x`**:**`xs`)**|**`p``x`**=**`x`**:**`filter``p``xs`**|**`otherwise`**=**`filter``p``xs`

- An alternative notation that combines the power of map and filter
`[2*n | n <- [10..12]]`

[20,22,24]- Based on notation from set theory. Also found in earlier functional languages (Hope, KRC). Also found in Python.

[3

`*``n`**|**`n`**<-**[10**..**12],`even``n`]- The list of all , where n comes from
3

`*``n`and[10

**..**12]is even.`n` - Same as
`map`(3`*`) (`filter``even`[10**..**12])

`pythag``n`**=**[(`x`,`y`,`z`)**|**`x`**<-**[1**..**`n`],`y`**<-**[`x`**..**`n`],`z`**<-**[`y`**..**`n`],`x``^`2`+``y``^`2`==``z``^`2]