add :: Int -> Int -> Int add x y = x + y inc1 :: Int -> Int inc1 = add 1 inc2 :: Int -> Int inc2 = (+1) sub = \x y -> x - y -- Listen lg :: [a] -> Int lg [] = 0 lg (_:xs) = 1 + lg xs xmap f [] = [] xmap f (x:xs) = (f x) : (xmap f xs) -- xmap (+2) [1,2,3] quicksort [] = [] quicksort (x:xs) = quicksort [y | y <- xs, y=x] -- Lazy inf = inf -- wohldefiniert, aber nicht auswertbar callLazy:: Int -> Bool -> Bool callLazy x y = if x == 0 then True else y -- statische Bindung -- Anwendung auch vor Definition testBind a = let foo b = c+1 -- freie Variable c c = 10 -- wird hier gebunden in a + let c = 100 -- wird nicht im Aufruf von foo gebunden in foo 0 + foo 0 -- Unendliche Listen ones :: [Int] ones = 1 : ones numsFrom :: Int -> [Int] numsFrom n = n : numsFrom (n+1) squares :: [Int] squares = map (^2) (numsFrom 0) fib :: [Int] fib = 1 : 1 : [ a+b | (a,b) <- zip fib (tail fib) ] fibs :: [Int] fibs = 1 : 1 : (zipWith (+) fibs (tail fibs)) reqs = client csInit resps resps = server reqs client :: Int -> [Int] -> [Int] -- client init (resp:resps) = init : client (next resp) resps -- Fehler: das zweite Pattern wird zu fr\x{00FC}h ausgewertet -- client init resps = init : client (next (head resps)) (tail resps) -- funktioniert: Das zweite Pattern wird erst bei Benutzung ausgewertet client init ~(resp:resps) = init : client (next resp) resps -- Das zweite Pattern wird erst bei Benutzung ausgewertet server :: [Int] -> [Int] server (req:reqs) = process req : server reqs csInit = 0 next resp = resp process req = req+1 within :: Float -> [Float] -> Float within eps (x1:(x2:xs)) = if abs(x1-x2)a) -> a -> [a] myIterate f x = x : myIterate f (f x) nextApprox a x = (a / x + x) / 2.0 qroot a = within 1e-8 (myIterate (nextApprox a) 1.0) dupl = (*2) -- Type definitions data Color = Red | Green | Blue | Indigo | Violet -- vordefiniert: data [a] = [] | a : [a] data Tree a = Leaf a | Branch (Tree a) (Tree a) -- Branch :: Tree a -> Tree a -> Tree a -- Leaf :: a -> Tree a fringe :: Tree a -> [a] fringe (Leaf x) = [x] fringe (Branch left right) = fringe left ++ fringe right -- ++: Listenkonkatenation -- fringe (Branch (Branch (Leaf 1) (Leaf 2)) Branch ((Leaf 3) (Leaf 4)))