![haskell list comprehension haskell list comprehension](https://pic4.zhimg.com/v2-bb0ff37f9df0938a9a067e84ca3dafaa_r.jpg)
*Main> (take 1000 factorial1) = (take 1000 factorial2)Īnother common example when demonstrating infinite lists is the Fibonacci sequence - Wikipedia’s page on Haskell gives two ways of implementing this sequence as an infinite list - I’ll add another using scanl. Triangle2 = 1 : [x+y | x (take 1000 triangle1) = (take 1000 triangle2)
#Haskell list comprehension code
The following example code demonstrates both self referential list comprehension implementations, and those based on the built in scanl function (for the list comprehension examples, you’ll need to give ghci the -fglasgow-exts command line option): triangle1 = scanl (+) 1 The items in the list are built only when they are needed, generating previous items if necessary, so even though the sequence is potentially limitless, it wont take up an infinite amount of memory.Ī more complicated example is generating the sequence of factorial numbers and triangular numbers.
![haskell list comprehension haskell list comprehension](https://image3.slideserve.com/6459274/integers-l.jpg)
This works equally well with functions that produce lists, such as map, as with list comprehensions. Even though the list is never complete, we can build each item in the list by using the sequence’s latest value at that point in the program. When we look at the lists numbers1 and numbers2, the important thing is that each refers to itself in order to build the list. You can use it to generate linearly increasing or decreasing sequences concisely: *Main> Obviously, the third method here is the simplest, it’s the standard shorthand for linear sequences and acts like the range function in other languages. ) - there are a few different ways of doing this in Haskell: numbers1 = 1 : map (+1) numbers1 The simplest example of this is the sequence of natural numbers (ie. Since data types are lazy and support self references, you can produce a list dynamically by defining it as a function of its successors. Programming with infinite lists open up a new way of writing programs, where you give rules for generating a sequence rather than building it by hand - often leading to simpler code. In this article we use simple sequences as lists of infinite length in a number of different ways to demonstrate how you can use this approach.
![haskell list comprehension haskell list comprehension](https://files.speakerdeck.com/presentations/6111b90f3a8d4362992b5ac2e958c721/slide_16.jpg)
Haskell uses a lazy evaluation system which allows you define as many terms as you like, safe in the knowledge that the compiler will only allocate the ones you use in an expression.