




Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
This course is an introduction to concepts in programming languages. The course covers a range of programming paradigms including procedural, functional, and logic-based languages. This lecture includes: Recursion, Occurs Check Error, Haskell, Recursion, Binary Search, Pattern Matching, Series of Equations
Typology: Study notes
1 / 8
This page cannot be seen from the preview
Don't miss anything!





Today ...
Homework
Q: How can we define flatten in Haskell?
flatten xs = if null xs then xs -- this doesn’t work! else head xs ++ flatten (tail xs)
Q: What is the type of flatten?
Q: How can we fix this?
flatten :: [[a]] -> [a] flatten xs = if null xs then [] -- this works! else head xs ++ flatten (tail xs)
Q: Why does this work?
Q: How can we change minL to behave better?
minL’ xs = if null (tail xs) then head xs else let m = minL’ (tail xs) in if head xs <= m then head xs else m
Or using where instead:
minL’ xs = if null (tail xs) || head xs <= m then head xs else m where m = minL’ (tail xs)
Binary search is a classic example of recursion ...
quot 2 ⇒ 1)binSearch :: Ord a => a -> [a] -> Bool binSearch x ys = if null ys then False else if x == midval then True else if x < midval then binSearch x (take mid ys) else binSearch x (drop (mid+1) ys) where mid = (length ys) quot 2 midval = ys !! mid
A more involved example with lists ...
mix1 xs ys = if null xs || null ys then xs ++ ys else head xs : head ys : mix1 (tail xs) (tail ys)
Q: What do the following return?
mix1 [] [] ==> []
mix1 [1,3,5] [] ==> [1,3,5]
mix1 [] [2,4,6] ==> [2,4,6]
mix1 [1,3,5] [2,4,6] ==> [1,2,3,4,5,6]
Q: What are the patterns?
The mix function defined using patterns
mix2 [] ys = ys mix2 xs [] = xs mix2 xs ys = head xs : head ys : mix2 (tail xs) (tail ys)