130 likes | 259 Vues
This article delves into the Haskell programming language's built-in `take` function, which serves as a fundamental example of functional programming concepts. The `take` function extracts a specified number of elements from an infinite list, demonstrating the lazy evaluation characteristic of Haskell. We explore the execution steps of `take` through an infinite list, breaking down the recursive definition of the function and showing how it processes inputs. By analyzing the example `take 3 [1..]`, we gain insights into the inner workings of functional programs in Haskell.
E N D
Formal Models of Computation Running Haskell Programs - take
How functional programs work… take 0 xs = [] take (n+1) (x:xs) = x:(take n xs) Main> take 3 [1..] [1,2,3] • Comments: • [1..] is an infinite data structure • take is built-in in Haskell • If you want to try the definition above, change its name to myTake or something like that… formal models of computation
How functional programs work… Execution: take 0 xs = [] take (n+1) (x:xs) = x:(take n xs) take 3[1..] • 3matches(n+1)assigning 2 to n • The infinite list [1..] matches (x:xs), assigning 1 to x and [2..] (aha!) to xs formal models of computation
How functional programs work… Execution: take 0 xs = [] take (n+1) (x:xs) = x:(take n xs) take 3 [1..] 1:(take 2 [2..]) formal models of computation
How functional programs work… Execution: take 0 xs = [] take (n+1) (x:xs) = x:(take n xs) take 3 [1..] 1:(take 2 [2..]) formal models of computation
How functional programs work… Execution: take 0 xs = [] take (n+1) (x:xs) = x:(take n xs) take 3 [1..] 1:(take 2 [2..]) • 2matches(n+1)assigning 1 to n • The infinite list [2..] matches (x:xs), assigning 2 to x and [3..] to xs formal models of computation
How functional programs work… Execution: take 0 xs = [] take (n+1) (x:xs) = x:(take n xs) take 3 [1..] 1:(2:(take 1 [3..])) formal models of computation
How functional programs work… Execution: take 0 xs = [] take (n+1) (x:xs) = x:(take n xs) take 3 [1..] 1:(2:(take 1 [3..])) formal models of computation
How functional programs work… Execution: take 0 xs = [] take (n+1) (x:xs) = x:(take n xs) take 3 [1..] 1:(2:(take 1 [3..])) • 1matches(n+1)assigning 0 to n • The infinite list [3..] matches (x:xs), assigning 3 to x and [4..] to xs formal models of computation
How functional programs work… Execution: take 0 xs = [] take (n+1) (x:xs) = x:(take n xs) take 3 [1..] 1:(2:(3:(take 0 [4..]))) formal models of computation
How functional programs work… Execution: take 0 xs = [] take (n+1) (x:xs) = x:(take n xs) take 3 [1..] 1:(2:(3:(take 0 [4..]))) formal models of computation
How functional programs work… Execution: take 0 xs = [] take (n+1) (x:xs) = x:(take n xs) take 3 [1..] 1:(2:(3:[]))) formal models of computation
How functional programs work… Execution: take 0 xs = [] take (n+1) (x:xs) = x:(take n xs) take 3 [1..] [1,2,3] formal models of computation