Created
March 12, 2020 23:46
-
-
Save dbramucci/7e877d1e8b115911c9630c2cc42fabef to your computer and use it in GitHub Desktop.
A cool demonstration of complex lazy evaluation and recursive list definitions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
hailstone :: [[Int]] | |
hailstone = [] : [1] : map (\n -> let n' = collatz n in n : (hailstone !! n')) [2..] | |
collatz n = if even then half else 3 * n + 1 | |
where | |
(half, r) = n `quotRem` 2 | |
even = r == 0 | |
{- GHCI output, _ means that part hasn't been evaluated yet | |
Prelude> hailstone !! 3 | |
[3,10,5,16,8,4,2,1] | |
Prelude> :sprint hailstone | |
hailstone = [] : [1] : [2,1] : [3,10,5,16,8,4,2,1] : [4,2,1] : | |
[5,16,8,4,2,1] : _ : _ : [8,4,2,1] : _ : [10,5,16,8,4,2,1] : _ : | |
_ : _ : _ : _ : [16,8,4,2,1] : _ | |
Prelude> hailstone !! 7 | |
[7,22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1] | |
Prelude> :sprint hailstone | |
hailstone = [] : [1] : [2,1] : [3,10,5,16,8,4,2,1] : [4,2,1] : | |
[5,16,8,4,2,1] : _ : | |
[7,22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1] : [8,4,2,1] : _ : | |
[10,5,16,8,4,2,1] : [11,34,17,52,26,13,40,20,10,5,16,8,4,2,1] : _ : | |
[13,40,20,10,5,16,8,4,2,1] : _ : _ : [16,8,4,2,1] : | |
[17,52,26,13,40,20,10,5,16,8,4,2,1] : _ : _ : | |
[20,10,5,16,8,4,2,1] : _ : | |
[22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1] : _ : _ : _ : | |
[26,13,40,20,10,5,16,8,4,2,1] : _ : _ : _ : _ : _ : _ : _ : | |
[34,17,52,26,13,40,20,10,5,16,8,4,2,1] : _ : _ : _ : _ : _ : | |
[40,20,10,5,16,8,4,2,1] : _ : _ : _ : _ : _ : _ : _ : _ : _ : _ : | |
_ : [52,26,13,40,20,10,5,16,8,4,2,1] : _ | |
:} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another run showing that you can partially evaluate the individual elements of
hailstone
.