###### Sprachumschaltung

Sie sind hier: Code10 - HOF Teil 2

# Code10 - HOF Teil 2

Dieser Code wurde während dem zweiten Teil der Vorlesung über Funktionen höherer Ordnung live erstellt und demonstriert. Einige Kommentare wurden nachträglich hinzugefügt.

Vorlesung10.hs — Haskell source code, 1 KB (2000 bytes)

## Dateiinhalt

```{-# LANGUAGE ScopedTypeVariables, NoMonomorphismRestriction #-}

--------------------
-- foldl
--------------------

-- foldl :: (a -> b -> a) -> a -> [b] -> a
-- foldr :: (b -> a -> a) -> a -> [b] -> a

my_product :: [Double] -> Double
my_product xs = foldl (*) 1 xs

my_and :: [Bool] -> Bool
my_and xs = foldl (&&) True xs

my_concat :: [[a]] -> [a]
my_concat = foldl (++) []

my_reverse :: [a] -> [a]
my_reverse = foldl mr_aux []
where
mr_aux :: [a] -> a -> [a]
mr_aux acc x = x : acc

my_last :: [a] -> a
my_last []     = error "my_last: empty list has no last element"
my_last (x:xs) = foldl ml_aux x xs
where
ml_aux :: a -> a -> a
ml_aux acc x = x

my_last' :: [a] -> a
my_last' l = foldl1 ml_aux l
where
ml_aux :: a -> a -> a
ml_aux acc x = x

--------------------
-- foldr
--------------------

my_sum2 :: [Double] -> Double
my_sum2 xs = foldr (+) 0 xs

my_and2 :: [Bool] -> Bool
my_and2 = foldr (&&) True

my_length :: [a] -> Int
my_length xs = foldr (\x acc-> 1+acc) 0 xs
{-
my_length []    = 0
my_length (_:t) = 1 + my_length t
-}

my_map :: (x->y) -> [x] -> [y]
-- my_map f xs = foldr (\x acc -> f x : acc ) [] xs
my_map f xs = foldr my_map_aux [] xs
where
-- my_map_aux :: (u -> [v] -> [v])  Typsignatur kann nicht angegeben werden, da f frei vorkommt!
my_map_aux x acc = f x : acc
-- Typnebenrechnung:
-- f :: x -> y
-- foldr :: (x -> [y] -> [y]) -> [y] -> [x] -> [y]

my_map' f xs = foldr (my_map_aux f) [] xs
where
{- Abhilfe: explizite Übergabe von f: -}
my_map_aux :: (u -> v) -> (u -> [v] -> [v])
my_map_aux f x acc = f x : acc

my_filter :: (a->Bool) -> [a] -> [a]
my_filter f xs = foldr aux [] xs
where
aux x acc
| f x       = x : acc
| otherwise =     acc

my_elem :: (Eq a) => a -> [a] -> Bool
my_elem x xs = foldr aux False xs
where
aux z acc
| z == x    = True
| otherwise = acc

```

Artikelaktionen

abgelegt unter: