git.iko.soy/Haskell-HSE/haskell-lectures-2024
on main help sign in
61 lines 1.5 kB history raw
1# Laziness in Haskell
3Haskell is a functional language based on typed lambda calculus where
4everything is a well-typed expression, meaning it would allow you to do the
5following:
7```haskell
8apply :: (Int -> Int) -> Int
9apply f = f (apply f)
10```
12In most other languages, trying to evaluate this function on any argument would
13lead to stack overflow. However, the following safely terminates in Haskell
14(as it should):
16```haskell
17value = apply (\_ -> 5)
18-- apply (\_ -> 5) = (\_ -> 5) (apply (\_ -> 5)) = 5
19```
21This is possible thanks to the special runtime system of Haskell, or RTS for
22short. It computes values lazily rather than eagerly; this means that
24Rust: nom
26```haskell ignore
27foldr :: (a -> b -> b) -> b -> [a] -> b
28foldr f b [] = b
29foldr f b (x : xs) = f x (foldr f b xs)
30-- foldr (:) [] [1..1000] = 1 : foldr (:) [] [2..1000] =
31-- 1 : 2 : foldr (:) [] [3..1000]
33foldl :: (b -> a -> b) -> b -> [a] -> b
34foldl _ b [] = b
35foldl f b (x : xs) = foldl f (f b x) xs
36-- foldl (;) [] [1..1000] = foldl (;) (1 : []) [2..1000]
37-- = foldl (;) (2 : 1 : []) [3..1000] = ...
38```
40```haskell
41foldl' :: (b -> a -> b) -> b -> [a] -> b
42foldl' _ b [] = b
43foldl' f b (x : xs) =
44 let b' = f b x
45 in b' `seq` foldl' f b' xs
47-- ($!)
49foldl'' :: (b -> a -> b) -> b -> [a] -> b
50foldl'' _ !b [] = b
51foldl'' f !b (x : xs) = foldl'' f (f b x) xs
52```
54Strict fields in records
56```haskell
57data Point = Point {
58 x :: !Integer,
59 y :: ![Integer]
61```