Date post: | 29-Aug-2014 |
Category: |
Education |
Upload: | bryan-osullivan |
View: | 3,612 times |
Download: | 2 times |
Real World Haskell:Lecture 1
Bryan O’Sullivan
2009-10-07
Welcome!
A few things to mull over:
I Our pace will be fairly rapid.
I Stop me and ask questions—early and often.
I I assume no prior Haskell or functional programming exposure.
What’s software, doc?
What does a program do?
I It consumes old data.
I It computes over the old data.
I It produces new data.
A familiar program
Consider the Unix sort command:
I Consumes (possibly unsorted) lines of text.
I Sorts the lines.
I Produces sorted lines of text.
Have you ever run sort?
If so, you’re already a functional programmer.
What’s functional programming?
DefinitionFunctional programming is a style of programming that emphasizesfunctions and function application.
What’s a function?
DefinitionA function inspects its input, and produces an output.
DefinitionFunction application involves supplying a function with one ormore arguments (inputs).
Why is the sort command functional?
Discuss.
So what?
I can already write code that inspects inputs and produces outputsin C, Python, or whatever.
So what’s different about functional programming (FP)?
I We only inspect inputs; we don’t change them.
I In fact, we generally don’t change any data.
What’s interesting about functional programming?
I’ll tell you what got me hooked:
I It requires a substantially different way of thinking aboutprogramming.
I In exchange for the challenge, it offers great expressivenessand conciseness.
I It is beautiful.
Why Haskell?
Why choose Haskell over Erlang, Clojure, F#, OCaml, . . . ?
I It is the most radical of the practical functional languages.
I It will force you to learn many new things at once,
I and to unlearn things that perhaps you thought you knew.
Getting started with Haskell
We’ll be using the Haskell Platform:
I http://hackage.haskell.org/platform/
What is this Platform, anyway?
I A modern, optimising compiler (ghc)
I An interactive interpreter (ghci)
I Useful standard libraries
I An awesome package manager (cabal)
Starting with interaction
The interactive interpreter for the Haskell Platform is named ghci(for “GHC interactive”). When you run it, you’ll see something likethis:
GHCi, version 6.10.3: http://www.haskell.org/ghc/:? for help
Loading package ghc-prim ... linking ... done.Loading package integer ... linking ... done.Loading package base ... linking ... done.Prelude>
That “Prelude>” is the prompt.
Really simple stuff
What happens when you enter these expressions at the ghciprompt?
I 2+2
I putStrLn ”hi mom!”
I ”foo” ++ ”bar”
I :quit
Handy things to know
I You should be able to use your arrow keys to edit your ghciinput.
I Up and down arrows should go through your input history.
I Tab should complete names: try typing put<TAB>.
Haskell source files
I The standard Haskell source file extension is “.hs”.
I By convention, files use InterCapsNaming.
I Save the following in a file named Hello.hs:
main = putStrLn ” h e l l o , w o r l d ! ”
Run your program immediately
I We can run our new program straight away, via the runghcbatch interpreter:
$ runghc Hello.hshello, world!
Compilation
I We can also compile our new program to a native executable:
$ ghc --make Hello[1 of 1] Compiling Main ( Hello.hs, Hello.o )Linking Hello ...
I (GHC’s “--make” option is super-useful!)
I We can run our new program in the usual way:
$ ./Hellohello, world!
Operators and things
Haskell’s rules for writing expressions with operators should lookfamiliar.
bˆ2 − 4∗a∗c
I The ˆ operator is (integral) exponentiation.
I Expressions group as you might expect, i.e. (bˆ2) − (4∗a∗c).
Confused about operator precedence? Parens are your friend!
What about functions?
To apply a function to some arguments, we simply write it next toits arguments.
I length ”hello”
Function application binds tighter than operations, so if you writethis:
I sqrt 2 − 3
What you’ll get is this:
I (sqrt 2) − 3
If you mean something else, tell the compiler!
I sqrt (2 − 3)
A more complex expression
Look familiar?
I (−b + sqrt (bˆ2 ∗ 4∗a∗c)) / (2∗a)
(It’s part of the solution to a quadratic equation.)
Expressions are all very well
But we need a bit more to do anything useful.
I We have to be able to give things names.
To define something, we supply a name, an equals sign, and anexpression.
e = 2.718281828459045
A more useful definition
When we supply more than one name before the equals sign, theremainder are the arguments to a function.
oneRoot a b c = (−b + ( bˆ2 + 4∗a∗c ) ) / (2∗ a )
We’ve now defined a function named oneRoot, with threearguments.
I Try saving this definition into a source file, then load it intoghci and use it.
I What’s the result of this expression in ghci?
oneRoot 2 3 4
Your turn!
I’m going to open up an Emacs window.
I Tell me how to write a function that computes the mean ofthree numbers.
Speaking of Emacs
What are the best tools for working with Haskell source code?
I Emacs
I vim
Google for “emacs haskell mode” or “vim haskell mode” for details.
Do you prefer IDEs?
I At least for now, you’ve come to the wrong language. Back toVisual Studio with you!
I Less flippant answer: there are no mature Haskell IDEs yet.
Of source files and editors
Haskellers hate tab characters! (For the same reason Pythonprogrammers do: they’re unportable.)
A decent Haskell mode for a good editor will give you some usefulfeatures:
I Syntax highlighting.
I Intelligent indentation.
I Compilation and jump-to-error support.
I No tabs!
I Maybe interaction with ghci.
A very tiny, marginally useful program
wordCount xs = show ( length ( words xs ) ) ++ ”\n”
main = i n t e r ac t wordCount
What’s going on here?
I The words function breaks up a text string into a list of words.
I The length function. . . well, you can guess.
I The show function takes something (in this case, a number)and represents it as a string.
I The ++ operator means “append.”
Oh, and then there’s interact
The interact function is your gateway to Unix shell pipeline bliss.It:
I reads from standard input;
I feeds it to your function as a string;
I consumes the string that your function produces; and
I prints it to standard output.
Another very tiny program
I need your help!
Who can suggest what’s going on here?
import Data . L i s t ( so r t )
s o r t L i n e s xs = un l i nes ( so r t ( l i n e s xs ) )
main = i n t e r ac t s o r t L i n e s
Figuring stuff out
When you’re in exploratory mode (i.e. most of the time, at leastfor me), ghci is your friend.
Wonder what lines does? Simply try it, and find out!
Prelude> lines "foo\nbar\nquux\n"["foo","bar","quux"]
What else did we find out here?
Lists
The syntactic sugar for a list of items is square bracketssurrounding items, which are separated by commas:
[ 4 , 8 , 1 5 , 1 6 , 2 3 , 4 2 ][ True , False ][ ” L inden ” , ”Lab” ]
Let’s try some experiments with lists.
I Can we write this? [7,True]
I What about this? [[1,2],[3,4]]
More experimentation
I What does the unlines function do?
I What about sort?
Another small program
Let’s develop something! Another Unix-like command!
We’ll write a program that prefixes each line of input with a linenumber.
Okay. . . so now what?
When in doubt
If I don’t know how to solve a problem, I like to start by seeing ifthere are bits of it I know how to solve.
What do we already know about?
I Defining new functions!
I And, of course, using existing functions!
I We have a small library of built-in functions and operators,e.g. show, unlines, and ++.
The small problem
Given one number and one line of text, how should we renderthem?
oneNumber n s = show n ++ ” : ” ++ s
Let’s try this function in ghci:
Prelude> oneNumber 3 "blargh""3: blargh"
The small problem
Given one number and one line of text, how should we renderthem?
oneNumber n s = show n ++ ” : ” ++ s
Let’s try this function in ghci:
Prelude> oneNumber 3 "blargh""3: blargh"
The small problem
Given one number and one line of text, how should we renderthem?
oneNumber n s = show n ++ ” : ” ++ s
Let’s try this function in ghci:
Prelude> oneNumber 3 "blargh""3: blargh"
Powering up
That’s a good start. But now what?
We need to produce a whole series of lines with numbers.
l i n e N u m b e r s n xs =i f xs == [ ]then [ ]e l s e oneNumber n ( head xs )
: l i n e N u m b e r s ( n+1) ( t a i l xs )
Hey! See that little lonely “:”? It’s a list constructor (like cons inLisp or Scheme).
Powering up
That’s a good start. But now what?
We need to produce a whole series of lines with numbers.
l i n e N u m b e r s n xs =i f xs == [ ]then [ ]e l s e oneNumber n ( head xs )
: l i n e N u m b e r s ( n+1) ( t a i l xs )
Hey! See that little lonely “:”? It’s a list constructor (like cons inLisp or Scheme).
Powering up
That’s a good start. But now what?
We need to produce a whole series of lines with numbers.
l i n e N u m b e r s n xs =i f xs == [ ]then [ ]e l s e oneNumber n ( head xs )
: l i n e N u m b e r s ( n+1) ( t a i l xs )
Hey! See that little lonely “:”? It’s a list constructor (like cons inLisp or Scheme).
The quantum leap
Wow, we just did something interesting:
I We wrote a recursive function.
Not bad for the first lecture!
We still lack a little glue to create a complete program.
b u n c h i e xs = unwords ( l i n e N u m b e r s 1 ( l i n e s xs ) )
main = i n t e r ac t b u n c h i e
The quantum leap
Wow, we just did something interesting:
I We wrote a recursive function.
Not bad for the first lecture!
We still lack a little glue to create a complete program.
b u n c h i e xs = unwords ( l i n e N u m b e r s 1 ( l i n e s xs ) )
main = i n t e r ac t b u n c h i e
The quantum leap
Wow, we just did something interesting:
I We wrote a recursive function.
Not bad for the first lecture!
We still lack a little glue to create a complete program.
b u n c h i e xs = unwords ( l i n e N u m b e r s 1 ( l i n e s xs ) )
main = i n t e r ac t b u n c h i e
Accompanying materials
Where should you be going to learn more?
I http://book.realworldhaskell.org/
I http://learnyouahaskell.com/
I http://haskell.org/
I http://slideshare.net/bos31337
I #haskell on irc.freenode.net (I’m bos)
Source code for these slides and examples:
I darcs get http://darcs.serpentine.com/rwh-course
Accompanying materials
Where should you be going to learn more?
I http://book.realworldhaskell.org/
I http://learnyouahaskell.com/
I http://haskell.org/
I http://slideshare.net/bos31337
I #haskell on irc.freenode.net (I’m bos)
Source code for these slides and examples:
I darcs get http://darcs.serpentine.com/rwh-course
Recap
What have we covered today?
I What functional programming is. A tiny bit about Haskell.
I The Haskell Platform, and why it matters.
I Writing expressions, and defining functions.
I Simple interactive Unix-like commands.
There will be homework. Assignments will go out later today tothe haskell mailing list.
Thanks! Questions?
Recap
What have we covered today?
I What functional programming is. A tiny bit about Haskell.
I The Haskell Platform, and why it matters.
I Writing expressions, and defining functions.
I Simple interactive Unix-like commands.
There will be homework. Assignments will go out later today tothe haskell mailing list.
Thanks! Questions?
Recap
What have we covered today?
I What functional programming is. A tiny bit about Haskell.
I The Haskell Platform, and why it matters.
I Writing expressions, and defining functions.
I Simple interactive Unix-like commands.
There will be homework. Assignments will go out later today tothe haskell mailing list.
Thanks! Questions?