Page 1 of 1

A Gentle Haskell Intro, with pictures!

Posted: Fri Dec 24, 2004 12:25 am
by wtd
This is a repost of a tutorial posted at compsci.ca. Feel free to ask questions. :)

Disclaimer

This is yet another attempt to bring the ideas of functional programming to the masses here, and an experiment in finding ways to make it easy and interesting to follow.

Your feedback would be good as a means of judging my progress.

Why should you care?

Functional programming is fundamentally a very different way of thinking about programming. After all, we can learn several languages and pat ourselves on the back, but if the only real difference is syntactic, then we're not really being challenged.

What do I need?

You'll need either a Haskell interpreter or compiler. For learning purposes the Hugs Haskell interpreter is fine.

You can download it from: http://www.haskell.org/hugs/

It installs as easily as any other Windows program, and an entry will be created in the Start menu under: Start -> Programs -> Hugs98.

If you're running Windows 98 or ME, it would probably be wise to restart your computer, just to make sure everything the installer did takes effect. Windows 2000 and XP are pretty good about immediately applying the changes.

Oh, and you'll want a good text editor. I suggest TextPad with the Haskell syntax coloring file. Directions for installing the syntax file are available.

A quick look at Hugs

Start -> Programs -> Hugs98 -> Nov2003 -> Hugs (Haskell98 mode)

Image

So, at startup of Hugs we've got some ASCII art, copyright information, some basic usage tips, and a prompt. This is a good start.

What can we do with this?

Well, we can evaluate expressions and see their results.

What's an expression?

An expression is a little bit of code that takes one or more values and gives you a new value.

Consider this very simple example.

Image

Moving on

But really, we could do basic math all day and be bored out of our skulls, so let's look at putting together a source file where we can build more complex things.

A Haskell source file is just a text file containing Haskell code. The extension we use is ".hs".

So, what will our source file contain? A simple hello world program.

Code: Select all

module Main where

main = putStrLn "Hello, world!"[code]

What do we have here?  

Well, first of all we have to deal with the fact that Haskell code is organized into modules.  Modules allow us to easily reuse code in other programs, and they allow the actual language itself to be relatively simple.  The name of the file should match the name of the module.  Here the module is named "Main".

Next we have the "main" function, the center of activity, as in many other programming languages.  The ease of creating this function shouldn't come as any surprise given the fact that Haskell focuses on functions.

[code]putStrLn "Hello, world!"[code]

Here we simply use the putStrLn function to print a string to the screen on its own line.  The similar putStr function does the same, but doesn't automatically skip to a new line.

[img]http://familygeek.com/haskell/hugs3.png[/img]

[b]Testing the code[/b]

So, how do we run the code in this file?

Well, open up your trusty Command Prompt window and "cd" to the directory where you saved your Main.hs file.

Once you're there, start Hugs by simply typing "hugs" and hitting enter.  Again we're back to:

[img]http://familygeek.com/haskell/hugs.png[/img]

To load the "Main" module we simply:

[code]Prelude> :load Main
Main>[code]

The prompt has changed to indicate we're now in the Main module, rather than the Prelude module.

And to run the main function:

[code]Main> main
Hello, world!

Main>[code]

[b]So, we've seen a little bit of Haskell[/b]

Is it scary?

If you say yes, that's not bad.  New things can be scary.  You'll get over it.

The real question, though, is: where do we go from here?

Well, since Haskell is a functional programming language, I'm thinking it might be good to see some more functions.

[b]Expanding on Hello, world[/b]

Anyone even moderately familiar with my other tutorials will recognize the pattern of starting with a simple hello world program and then expanding upon it.

So, let's create a function "greet" which takes a name and greets that person.

Our Main.hs looked like:

[code]module Main where

main = putStrLn "Hello, world!"[code]

Now we're going to expand it with:

[code]module Main where

main = greet "Bob"

greet name = putStrLn ("Hello, " ++ name ++ "!")[code]

Of course, what if we want just the greeting string?

[code]module Main where

main = greet "Bob"

greet name = putStrLn (greeting name)

greeting name = "Hello, " ++ name ++ "!"[code]

[b]Tidying the code up - Haskell tricks[/b]

Haskell by default infers the types of data being used in a program, but for documentation purposes, we can explicitly specify the types a function uses and returns.

Doing this, we write a type signature for main.  The "main" function does an IO action, and returns the closest thing you can get in Haskell to nothing, so:

[code]module Main where

main :: IO ()
main = greet "Bob"

greet name = putStrLn (greeting name)

greeting name = "Hello, " ++ name ++ "!"[code]

Double colons separate the name of a function and its signature.

Continuing, we generate a signature for the "greet" and "greeting" functions.

[code]module Main where

main :: IO ()
main = greet "Bob"

greet :: String -> IO ()
greet name = putStrLn (greeting name)

greeting :: String -> String
greeting name = "Hello, " ++ name ++ "!"[code]

These signatures are saying, "greet takes a string as an argument and does an IO operation," and, "greeting takes a string as an argument and returns another string."

[code]greet name = putStrLn (greeting name)[code]

Here we use parentheses because otherwise this would be seen as putStrLn taking two arguments, "greeting" and "name".  Since putStrLn only takes one argument, this would clearly be erroneous.

But the parentheses can get annoying, so we have the $ operator.  Essentially, the $ operator takes the value on its right hand side and gives it to the function on the left hand side.  So, now our greet function looks like:

[code]greet name = putStrLn $ greeting name[code]

So, our code now looks like:

[code]module Main where

main :: IO ()
main = greet "Bob"

greet :: String -> IO ()
greet name = putStrLn $ greeting name

greeting :: String -> String
greeting name = "Hello, " ++ name ++ "!"[code]

[b]Input as well as output[/b]

All of this greeting isn't very much good unless we can get input from the user as well, to find out their name.  

IO actions aren't quite like other functions.  To "chain" them together in sequence we use the keyword "do".

[code]module Main where

main :: IO ()
main = do putStr "You are? "
          name <- getLine
          greet name

greet :: String -> IO ()
greet name = putStrLn $ greeting name

greeting :: String -> String
greeting name = "Hello, " ++ name ++ "!"[code]

Probably the most immediately notiecable change is the use of indentation.  Haskell uses what's referred to as "layout", so semi-colons and braces aren't necessary.  They are available:

[code]main = do { putStr "You are? ";
name <- getLine;
greet name }[code]

Of course, the "layout" approach is so much nicer that it'd be silly to use braces and semi-colons.

The second new bit of syntax is:

[code]name <- getLine[code]

The return of getLine is a string, but an IO "tainted" string, which can't be immediately used.  Using the <-  syntax, "name" is a plain old string we can use elsewhere.

[b]Conditionals[/b]

How about when the name given to the greeting function is "Haskell", the greeting is "Hey, whadda ya know?  This is a Haskell program!"

[code]module Main where

main :: IO ()
main = do putStr "You are? "
          name <- getLine
          greet name

greet :: String -> IO ()
greet name = putStrLn $ greeting name

greeting :: String -> String
greeting name = 
  if name == "Haskell"
    then "Hey, whadda ya know?  This is a Haskell program!"
    else "Hello, " ++ name ++ "!"[code]

This should look fairly straightforward to a programmer with basic experience in other languages.  Also, again we use "layout" to signify the structure of the conditional.

[b]Case expressions[/b]

Let's say we want our program to greet "Matz" with, "You make a good language."  Using only "if":

[code]module Main where

main :: IO ()
main = do putStr "You are? "
          name <- getLine
          greet name

greet :: String -> IO ()
greet name = putStrLn $ greeting name

greeting :: String -> String
greeting name = 
  if name == "Haskell"
    then "Hey, whadda ya know?  This is a Haskell program!"
    else if name == "Matz"
           then "You make a good language."
           else "Hello, " ++ name ++ "!"[code]

Wow, that's ugly.  Fortunately, we have the case expression that should look familiar to programmers.

[code]module Main where

main :: IO ()
main = do putStr "You are? "
          name <- getLine
          greet name

greet :: String -> IO ()
greet name = putStrLn $ greeting name

greeting :: String -> String
greeting name = 
  case name of
    "Haskell" -> "Hey, whadda ya know?  This is a Haskell program!"
    "Matz"    -> "You make a good language."
    otherwise -> "Hello, " ++ name ++ "!"[code]

As with "if", we use layout.

[b]Overloading functions[/b]

Of course, we can do this even more cleanly by overloading the greeting function.

[code]module Main where

main :: IO ()
main = do putStr "You are? "
          name <- getLine
          greet name

greet :: String -> IO ()
greet name = putStrLn $ greeting name

greeting :: String -> String
greeting "Haskell" = "Hey, whadda ya know?  This is a Haskell program!"
greeting "Matz"    = "You make a good language."
greeting name      = "Hello, " ++ name ++ "!"[code]

[b]Loops[/b]

At this point you might be tempted to ask how Haskell handles looping, since that's a pretty basic thing for programmers to learn about in other languages.

Haskell provides no special syntax for looping.  All looping is achieved via recursion, where a function calls itself.

[code]module Main where

main :: IO ()
main = do putStr "You are? "
          name <- getLine
          if name == "quit"
            then return ()
            else do greet name
                    main

greet :: String -> IO ()
greet name = putStrLn $ greeting name

greeting :: String -> String
greeting "Haskell" = "Hey, whadda ya know?  This is a Haskell program!"
greeting "Matz"    = "You make a good language."
greeting name      = "Hello, " ++ name ++ "!"[code]

A few questions that may come up from looking at this:
<ul><li>What does [code]return ()[code] do?  This basically turns () into IO (), which is the return our main function wants.</li><li>Why is "do" repeated in the "if" expression?  The "if" basically "interrupts the chain of expressions we were creating.  To start another "chain" we need to use "do" again.</li></ul> 

[color=#888888][size=85]Archived topic from Iceteks,  old topic ID:2947, old post ID:24032[/size][/color]

A Gentle Haskell Intro, with pictures!

Posted: Fri Dec 24, 2004 12:41 am
by Red Squirrel
Hey would you mind writing that as an article so it can be posted in the article section? Some useful info there. :)

Archived topic from Iceteks, old topic ID:2947, old post ID:24033

A Gentle Haskell Intro, with pictures!

Posted: Fri Dec 24, 2004 12:48 am
by wtd
What are the requirements for that?

Archived topic from Iceteks, old topic ID:2947, old post ID:24034

A Gentle Haskell Intro, with pictures!

Posted: Fri Dec 24, 2004 1:22 am
by Red Squirrel
Not much, just write what you would like it to look like as an actual article and send it to me by PM or email. The way it is here is good so if that's how you want it to look then I just need an ok to copy and paste it as an article. ;)

It's sent to quite a few sites to post so it will get quite allot of exposure.

Archived topic from Iceteks, old topic ID:2947, old post ID:24035

A Gentle Haskell Intro, with pictures!

Posted: Sat Sep 17, 2005 3:13 pm
by Anonymous
That is the reaction of most people when I tell them I ride a recumbent bicycle. Or they nod sagely and say, "Oh yes, my gym has one of those," visualizing me pedaling a stationary exercise bike. Then I explain that I ride a recumbent on the road, which confuses them even more. "it's a laid-back bicycle with a chair-like seat," I explain, "and I ride it because it’s fun, fast, and supremely comfortable." A comfortable bicycle? How radical!

Archived topic from Iceteks, old topic ID:2947, old post ID:30125

A Gentle Haskell Intro, with pictures!

Posted: Sat Sep 17, 2005 3:31 pm
by Red Squirrel
huh?

Archived topic from Iceteks, old topic ID:2947, old post ID:30127

A Gentle Haskell Intro, with pictures!

Posted: Sat Sep 17, 2005 8:54 pm
by Triple6_wild
what was the point of that post?

Image

Archived topic from Iceteks, old topic ID:2947, old post ID:30132

A Gentle Haskell Intro, with pictures!

Posted: Sun Sep 18, 2005 10:00 pm
by Pyr-O-Rgasm
poser931 wrote: That is the reaction of most people when I tell them I ride a recumbent bicycle. Or they nod sagely and say, "Oh yes, my gym has one of those," visualizing me pedaling a stationary exercise bike. Then I explain that I ride a recumbent on the road, which confuses them even more. "it's a laid-back bicycle with a chair-like seat," I explain, "and I ride it because it’s fun, fast, and supremely comfortable." A comfortable bicycle? How radical!
Just nod your head and pretend you understand. :huh:

Archived topic from Iceteks, old topic ID:2947, old post ID:30146