Skip to content

Commit d0893f8

Browse files
committed
feat(examples): new examples
1 parent 6530fe5 commit d0893f8

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

examples/17-01-25.hs

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
-- let {assignments} in expression
2+
easy =
3+
let fn y = y*2
4+
y = 10
5+
in fn 2 + y
6+
7+
-- where
8+
9+
dot :: Num a => [a] -> [a] -> a
10+
dot xs ws = foldr (\(x, w) a -> x * w + a) 0 inputs
11+
where
12+
inputs = zip xs ws
13+
14+
dot' :: Num a => [a] -> [a] -> a
15+
dot' xs ws =
16+
let inputs = zip xs ws
17+
in foldr (\(x, w) a -> x * w + a) 0 inputs
18+
19+
20+
-- unterschied zwischen let und where
21+
-- let ist eine expression und überall erlaubt wo eine expression stehen darf
22+
-- expression ist etwas, was zu einem Wert evaluiert
23+
24+
25+
-- Abstraktere Folds
26+
-- Komplexere Datenstrukturen und Folds
27+
data BinTree a = Node a (BinTree a) (BinTree a)
28+
| Leaf a
29+
| Empty
30+
deriving (Eq, Show)
31+
32+
33+
bsp1 = Node 6 (Node 3 Empty (Leaf 5)) (Node 7 Empty (Leaf 2))
34+
35+
foldTree :: (a -> b -> b -> b) -> (a -> b) -> b -> BinTree a -> b
36+
foldTree fNode fLeaf fEmpty = fold
37+
where
38+
fold (Node a l r) = fNode a (fold l) (fold r)
39+
fold (Leaf a) = fLeaf a
40+
fold Empty = fEmpty
41+
42+
43+
countLeaves' :: BinTree a -> Int
44+
countLeaves' (Node _ l r) = countLeaves' l + countLeaves' r
45+
countLeaves' (Leaf _) = 1
46+
countLeaves' Empty = 0
47+
48+
49+
countLeaves :: BinTree a -> Int
50+
countLeaves = foldTree (\_ x y -> x + y) (const 1) 0
51+
52+
53+
removeLeafs :: BinTree a -> BinTree a
54+
removeLeafs = foldTree Node (const Empty) Empty
55+
56+
57+
sumTree :: Num a => BinTree a -> a
58+
sumTree = foldTree (\x l r -> x + l + r) id 0
59+
60+
leafify :: Eq a => BinTree a -> BinTree a
61+
leafify = foldTree
62+
(\x l r -> case (l,r) of
63+
(Empty, Empty) -> Leaf x
64+
_ -> Node x l r)
65+
Leaf
66+
Empty

0 commit comments

Comments
 (0)