CSE 341
section, July 8, 1999

This version of this page has no answers.

Jump to a section of this page...

  1. functions with pattern matching
  2. functions with guards
  3. cons (:) and append (++)
  4. functions on lists with pattern matching
  5. Name That Function (three parts)
  6. list comprehension and infinite lists

functions with pattern matching

-- the Fibonacci numbers,
-- arguably the most
-- famous sequence of
-- numbers in history

fib 0 = 1
fib 1 = 1
fib n = fib (n-1) + fib (n-2)


Main> fib 0
1
Main> fib 1 
1
Main> fib 2
2
Main> fib 3
3
Main> [0..10]
[0,1,2,3,4,5,6,7,8,9,10]
Main> map fib [0..10]
[1,1,2,3,5,8,13,21,34,55,89]

functions with guards

fib n | n > 1     = fib (n-1) + fib (n-2)
      | otherwise = 1


Main> map fib [0..16]
[1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597]

cons (:) and append (++)

Main> 12:[1,2,43]
[12,1,2,43]


Main> 12:12
ERROR: Illegal Haskell 98 class constraint in inferred type
*** Expression : 12 : 12
*** Type       : (Num a, Num [a]) => [a]


Main> 12:[]
[12]


Main> 'a':['b','c']
"abc"


Main> 'a':['b','c',2]
ERROR: Illegal Haskell 98 class constraint in inferred type
*** Expression : 'a' : ['b','c',2]
*** Type       : Num Char => [Char]


Main> [1,2,3]:[4,5]
ERROR: Illegal Haskell 98 class constraint in inferred type
*** Expression : [1,2,3] : [4,5]
*** Type       : (Num a, Num [a]) => [[a]]


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


Main> ['h','a','s']++['k','e','l','l']
"haskell"


Main> 'h':"askell"
"haskell"

functions on lists with pattern matching

revList [] = []
revList (x:xs) = (revList xs) ++ [x]

sumList [] = 0
sumList (x:xs) = x + (sumList xs)

listLength [] = 0
listLength (_:xs) = 1 + (listLength xs)

Main> [24,21..6]
[24,21,18,15,12,9,6]

Main> revList [24,21..6]
[6,9,12,15,18,21,24]


Main> sumList [3,2,-10]
-5


Main> listLength [1,5,3,7,4,2,3,3]
8

It's time to play...

Name That Function!

one 0 = 1
one n = n * one (n-1)

two 0 s = ""
two n s = s ++ (two (n-1) s)

three [] = []
three (x:xs) = (three xs) ++ [x]

four [] = 0
four (x:xs) = x + (four xs)

Main> one 5
???

Main> two 3 "ding"
???

Main> three [3,1,4,1,5,9,2,7]
???

Main> four [2,6,1976]
???


Here comes another exciting installment of...

Name That Function!!

unknown i [] = 0
unknown 1 (x:_) = x
unknown i (_:xs) = (unknown (i-1) xs)

Main> unknown 4 [2,1,5,3,23]
???

Yes, kids! Once again, it's...

Name That Function!!!

mystery [] = []
mystery (x:xs) = enigma x (mystery xs)

enigma x [] = [x]
enigma x (y:ys) | x <= y    = x:(y:ys)
                | otherwise = y:(enigma x ys)

Main> mystery [2,1,5,3,23]
???

list comprehension and infinite lists

powers n = [n^k | k<-[0..]]

evenPowers n = [n^k | k<-[0..], mod k 2 == 0]

Main> take 5 (powers 2)
[1,2,4,8,16]

Main> take 10 (powers 2)
[1,2,4,8,16,32,64,128,256,512]

Main> take 10 (evenPowers 2)
[1,4,16,64,256,1024,4096,16384,65536,262144]


Ken Yasuhara <yasuhara@cs.washington.edu>
Last modified: Thu Jul 8 15:17:37 PDT 1999