Streams in Haskell

Chapter: Streams in Haskell

Open up a unix shell or a unix shell in emacs and invoke Haskell now by typing ghci You will be shown a title page and a prompt:

Prelude>
This means that the Haskell prelude (containing many useful definitions) is the current module. As you will recall from last week, you can work with Haskell interactively, just like in Scheme (but without side-effects). Here is a short transcript:
Prelude> 2 + 2
4
Prelude> [1..20]
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
Prelude> product [1..20]
2432902008176640000
Prelude> [n*n | n <- [1..20]]
[1,4,9,16,25,36,49,64,81,100,121,144,169,196,225,256,289,324,361,400]
Prelude>
Of course, you would like to be able to work with variables and to define functions. But Haskell has no side-effects! You can't do those things interactively. You can put definitions in a file and then reference that file from Haskell. Let's do that now.

Open a new emacs file called "first.hs". Type into it the following lines:

myvariable = 42

fac n = product [1..n]

billgates = "dollar" : billgates

Now in your Haskell shell, type :load first.hs. You should get a message about what's going on and then a new Haskell prompt. It just says Main> because we're not really using the module system. (Check the online tutorials if you want to do so.)

The first line shows you how to use = to assign a value to a variable. Test it now by typing 3 + myvariable. The second line shows you how to use = to make a function definition. Test it now by typing fac 100. The third line shows how you can take advantage of the lazy evaluation of Haskell to define an infinite list of "dollar"s. Test it now by typing billgates but be sure to be ready with a CTRL-c or two to interrupt the process. For a more manageable number of dollars try take 20 billgates.

You may like to load and experiment with my file: haskellexamples.hs.

where you will find 26 lines of Haskell code (many of which you have seen previously) that define:

The amazing thing is that such terse code remains remarkably readable.

Q. 6
What is the difference between "infinite list" and "unending stream"?



rhyspj@gwu.edu