Third Week FMFP
A bit late, but here you get the solutions from week three.
Usage of List
Multiply all numbers from 1 to 100 by using a prelude function (and no recursion)
foldr (*) 1 [1..100]
Sum all odd numbers bellow 50. Use a prelude function and the haskell list in a clever way.
sum [1,3..49]
Generate the string "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" (remember a string in haskell is just a list of chars)
['a'..'z'] ++ ['a'..'z']
List functions
sum :: (Num a) => [a] -> a sum [] = 0 sum (x:xs) = x + (sum xs) merge :: [a] -> [a] -> [a] -- merge two list (in haskell (++)) merge [] ys = ys merge (x:xs) ys = x : (merge xs ys) nthElement :: [a] -> Int -> a -- give the n-th element of a list (in haskell (!!)) nthElement (x:xs) 0 = x -- errors ignored nthElement (x:xs) n+1 = nthElement xs n
List comprehension
Find all numbers bellow 1000 that are devidable by 3 or 5 with a list comprehension.
[x | x <- [1..999], (mod x 3)==0 || (mod x 5)==0]
A Proof for the end
You can also do recursiv proofs over lists. Given the following programm:
map f [] = [] (m.1) map f (x:xs) = f x : map f xs (m.2) times2 x = 2*x (ti) twice [] = [] (tw.1) twice (x:xs) = (2* x):(twice xs) (tw.2)
Prove "FORALL xs::[int]. twice xs = map times2 xs" with recursion.
FORALL xs::[int]. twice xs = map times2 xs
Let P(xs) = twice xs = map times2 xs.
Show FORALL xs::[int]. P(xs) holds by induction over xs
Base case: P([])
twice [] = [] (tw.1)
= map times2 [] (m1.rev)
Step case: Show FORALL x::int, xs::[int]. P(xs) => P(x:xs) (IH = P(xs))
Twice (x:xs) = (2 * x):(twice xs) (tw.2)
= (times2 x):(twice xs) (ti.rev)
= (times2 x):(map times2 xs) (IH)
= map times2 (x:xs) (tw.2.rev)
comments
add a comment
The Trackback URL to this comment is:
http://leo.freeflux.net/blog/plugin=trackback(2833).xml
No new comments allowed (anymore) on this post.





