\input{haskpres.cfg} \documentstyle{fppres} \title{CCSC Haskell tutorial} \begin{document} \begin{presentation} {CCSC Haskell tutorial} {Fritz Ruehr}{1}{6 October 2001}{} \begin{slide}{Introduction to functional programming and Haskell} \slideitem{Functional languages: an alternative paradigm} Mainstream languages are imperative or object-oriented; functional programs are more like mathematical expressions, i.e., without {\bf side-effects} \slideitem{Lack of side-effects facilitates logical reasoning and formal methods} In traditional languages, even the simplest aspects of algebraic and equational reasoning can fail \haskon\begin{code}f(x) + f(x) == 2 * f(x) g(y) == g(y)\end{code}\haskoff \slideitem{A high-level perspective on programming} Powerful abstraction features (higher-order functions, polymorphic types, etc.) allow for very concise expression of programs and a high "signal-to-noise" ratio \haskon\begin{code}quicksort [] = [] quicksort (x:xs) = quicksort small ++ [x] ++ quicksort large where small = [y | y<-xs, y< x] large = [y | y<-xs, y>=x]\end{code}\haskoff \slideitem{Haskell and other functional programming languages} Most functional languages (LISP, APL, Scheme, ML) make concessions to side-effects; Haskell is a study in {\it pure} functional style (plus, it uses a familiar algebraic syntax) \slideitem{Regional relevance in the Northwest} \begin{itemize} \item \xlink{http://www.cse.ogi.edu/PacSoft}{the OGI Pacsoft group} is a world leader in Haskell and FP \item Intel uses Haskell and other FPs for hardware modeling and development \item \xlink{http://www.galoisconnections.com/}{Galois Connections}: a profitable private company with industrial and government contracts \item Microsoft has bought into Haskell, both in Cambridge and Redmond \end{itemize} \slideitem{Overview of the tutorial} \begin{itemize} \item basic syntax and features of Haskell (by example) \item short applications (text processing, number bases, DFA simulation, etc.) \item medium-sized example: generic sorting and simple database \item medium-sized example: parsing and evaluating a simple expression language \item medium-sized example: simple vector graphics package \item overview of larger applications and libraries (music, graphics, animation, GUIs, web, etc.) \end{itemize} \slideitem{Haskell tools and resources (see also the physical hand-out)} \begin{itemize} \item \xlink{http://www.haskell.org}{the Haskell.org website} \item \xlink{http://www.haskell.org/hugs/}{the Hugs interactive interpreter} \item \xlink{http://www.haskell.org/ghc/}{the GHC compiler and GHCi interactive system} \item \xlink{http://www.haskell.org/ghc/dist/5.02/ghc-5-02.exe}{the latest Windows GHC installer (v. 5.02)} \item \xlink{http://cm.bell-labs.com/cm/cs/who/wadler/realworld/}{functional programming in the real world} \end{itemize} \end{slide} \begin{slide}{Basic Haskell: interaction with the Hugs interpreter} \slideitem{A calculator-style interpretive interface} We'll use the Hugs interpreter: it provides an interactive command-line on which user expressions can be evaluated and printed \haskon\begin{code}> 2 +3 * 5 17 > reverse "Hello, world!" "!dlrow ,olleH"\end{code}\haskoff \slideitem{The "\$\$" short-cut} We can use a short-cut to refer to the last expression evaluated; this allows for a convenient exploratory paradigm \haskon\begin{code}> 2 + 3 * 5 17 > 2 ^ $$131072 >$$ mod 3 2 > replicate 3 "hello" ["hello","hello","hello"] > concat $$"hellohellohello" > length$$ 15\end{code}\haskoff \slideitem{Interpreter response versus printed output} The response we receive from Hugs is formatted to allow for easy re-entry; we can also print output in a more traditional format \haskon\begin{code}> "hello, world!" "hello, world!" > putStr $$hello, world!\end{code}\haskoff \slideitem{Interpreter commands} Hugs also supports a number of "meta-level" commands at the prompt, including the following useful ones: \begin{itemize} \item \hask{:t} -- reports the type of an expression \item \hask{:s +s} -- turns on resource statistics \item \hask{:n} -- looks up names based on patterns \item \hask{:l} -- loads program files to provide definitions \item \hask{:q} -- quits the interpreter \end{itemize} \end{slide} \begin{slide}{Basic Haskell: simple data types} \slideitem{Ints and Integers} The default Integer type in Haskell provides for very large numbers \haskon\begin{code}> 2 ^ 100 1267650600228229401496703205376 > 2 ^ 200 1606938044258990275541962092341162602522202993782792835301376\end{code}\haskoff (there is also a more efficient and traditional Int type) \slideitem{Floating-point arithmetic} Traditional IEEE floating-point arithmetic is also available (with the usual caveats) \haskon\begin{code}> 2.3 ^ 5 64.36343 >$$ * 25.333 1630.51877\end{code}\haskoff \slideitem{Exact rational arithmetic} Haskell provides exact rational numbers (written with an infix "\%") as a safer alternative to floating-point \haskon\begin{code}> 51 % 3 17 % 1 > (51 % 3) * (2 % 5) 34 % 5\end{code}\haskoff \slideitem{Booleans and {\tt if} expressions} The usual boolean values are written with initial caps; the conditional construct is an {\it expression}, not a {\it statement} \haskon\begin{code}> if 3 < 2 then "oops" else "hurray!" "hurray!" > (if 3 < 2 then "oops" else "hurray!") ++ " arithmetic works!" "hurray! arithmetic works!" > (if 3 < 2 then (+) else (*)) 10 20 200\end{code}\haskoff \slideitem{Pairs and tuples} Unlike most languages, Haskell provides pairs and tuples as independent entities (e.g., to return multiple results) \haskon\begin{code}> fst (2, "foo") 2 > 17 divMod 3 (5,2)\end{code}\haskoff \slideitem{The Maybe type} The Maybe datatype marks values as either Nothing or "Just" a single value; this allows for a natural light-weight exception mechanism \haskon\begin{code}> lookup "sam" [("amy", 25), ("fred", 1), ("sam", 2)] Just 2 > lookup "jim" [("amy", 25), ("fred", 1), ("sam", 2)] Nothing\end{code}\haskoff \end{slide} \begin{slide}{Basic Haskell: lists and list notations} \slideitem{Lists in Haskell} Although Haskell provides for convenient definition of data types and structures, lists are pre-defined and ubiquitous (storage is automatically allocated and collected) \slideitem{Bracket notation} Lists can be written easily using square brackets and commas as delimiters \haskon\begin{code}> reverse [1, 2, 3, 4, 5] [5,4,3,2,1]\end{code}\haskoff \slideitem{Infix notation and head, tail, null} In fact, lists are defined as a recursive data type (as in LISP), constructed from the head (first item) and tail \haskon\begin{code}> head [1,2,3,4] 1 > tail [1,2,3,4] [2,3,4] > 1 : [2,3,4] [1,2,3,4] >\end{code}\haskoff (LISPs "cons" is written with an infix colon) \slideitem{Ellipses for ordered domains} As a convenient further short-hand, lists over ordered domains can be written with a special ellipsis notation \haskon\begin{code}> [1..10] [1,2,3,4,5,6,7,8,9,10] > [0,2..20] [0,2,4,6,8,10,12,14,16,18,20]\end{code}\haskoff \slideitem{Strings as lists of characters} In fact, Haskell's strings are just lists over the atomic Char type (by default, they are printed using the quoted form) \haskon\begin{code}> :t "hello" "hello" :: String > ['h', 'e', 'l', 'l', 'o'] "hello" > ['a'..'z'] "abcdefghijklmnopqrstuvwxyz"\end{code}\haskoff \slideitem{Component and lists types} Haskell lists are polymorphic but homogeneous: different lists may hold different types of elements, but a single list must hold just one uniform type of element \haskon\begin{code}> [True, False, True] [True,False,True] > :t  [True,False,True] :: [Bool] > :t reverse reverse :: [a] -> [a]\end{code}\haskoff \slideitem{Convenient list functions} Many useful functions on lists are provided in a standard Prelude \haskon\begin{code}> length ['a'..'z'] 26 > [1..10] ++ reverse [1..10] [1,2,3,4,5,6,7,8,9,10,10,9,8,7,6,5,4,3,2,1]\end{code}\haskoff \slideitem{Infinite lists and lazy evaluation} Haskell provides {\bf lazy evaluation} for functions and data structures, so we can define infinite lists (it is prudent to avoid evaluation of a whole infinite list!) \haskon\begin{code}> [1,3..] [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,{Interrupted!} > take 20 [1,3..] [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39]\end{code}\haskoff \slideitem{Z-F expressions} One last notational convenience (due to David Turner) is {\bf list comprehension}, which mimics notation from Zermelo-Fraenkel set theory \haskon\begin{code}> [ a * b | a<-[1..3], b<-reverse [1..4] ] [4,3,2,1,8,6,4,2,12,9,6,3] > [ 2^i | i<-[1..10], odd i ] [2,8,32,128,512]\end{code}\haskoff \end{slide} \begin{slide}{Basic Haskell: higher-order functions} \slideitem{Currying} Haskell functions of several arguments are actually "curried", i.e., they are higher-order functions of successive arguments \haskon\begin{code}> :t take take :: Int -> [a] -> [a] > :t take 10 take 10 :: [a] -> [a] > :t take 10 ['a'..'z'] take 10 (enumFromTo 'a' 'z') :: [Char]\end{code}\haskoff \slideitem{Infix operators versus prefix functions} Infix operators are just curried functions; by default, symbolic identifiers are written infix and alphabetic ones prefix, but we can over-ride these defaults \haskon\begin{code}> :t (+) (+) :: Num a => a -> a -> a > (+) 10 20 30 > 10 divMod 3 (3,1)\end{code}\haskoff \slideitem{Operator sections} We can conveniently apply an infix operator to just one argument by enclosing the phrase in parentheses \haskon\begin{code}> (2^) 10 1024 > (^2) 10 100\end{code}\haskoff \slideitem{The map functional} The map functional takes a function as its first argument, then applies it to every element of a list \haskon\begin{code}> map (^2) [1..10] [1,4,9,16,25,36,49,64,81,100] > map (div 3) [1..20] [0,0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6] > map reverse ["hey", "there", "world"] ["yeh","ereht","dlrow"] > reverse ["hey", "there", "world"] ["world","there","hey"]\end{code}\haskoff \slideitem{Higher-order predicates} Predicates (boolean-valued functions) can be extended to lists via the higher-order predicates {\tt any} and {\tt all} \haskon\begin{code}> map even [1..5] [False,True,False,True,False] > all even (map (2*) [1..5]) True > any odd [ x^2 | x<-[1..5] ] True\end{code}\haskoff \slideitem{The fold functions} The fold functions {\tt foldl} and {\tt foldr} combine elements of a list based on a binary function and an initial value \haskon\begin{code}> foldr (+) 0 [1..10] 55 > sum [1..10] 55 > foldr (*) 1 [1..5] == 1 * 2 * 3 * 4 * 5 * 1 True > foldl (&&) True (map even [2,4..10]) True\end{code}\haskoff \slideitem{Other useful higher-order functions} The standard Prelude defines scores of useful functions, many of which enjoy great generality due to the abstractional capabilities of polymorphic types and higher-order functions \haskon\begin{code}> zipWith (*) [1..10] [1..10] [1,4,9,16,25,36,49,64,81,100] > :t replicate replicate :: Int -> a -> [a] > zipWith replicate [1..6] ['a'..'z'] ["a","bb","ccc","dddd","eeeee","ffffff"] > takeWhile (<100) [ 2^n | n<-[1..] ] [2,4,8,16,32,64] > :t takeWhile takeWhile :: (a -> Bool) -> [a] -> [a]\end{code}\haskoff \end{slide} \begin{slide}{Basic Haskell: script or program files} \slideitem{External text files for definitions} The interactive command line is quite powerful by itself, but for serious programming we need to make and use {\bf definitions}; this is done in external files, which are then loaded into the interpreter \slideitem{"Off-side" rule uses layout to control structure} Haskell program files are just series of definitions (values, functions, data types, etc.) which may refer to each other (and themselves, recursively) Layout is used to control the nesting of local clauses in definitions: this leads to less need for punctuation \slideitem{"Literate script" option} In a standard Haskell file ({\tt ".hs"} suffix) comments are set off from code (using {\tt "--"} or {\tt "\{- ... - \}" } A second form, the "literate style ({\tt ".lhs"} suffix) inverts the normal code/comment relationship: code must be set off (with a {\tt "> "} prefix) \slideitem{Simple modules system for control of namespaces} Although Haskell does not have a sophisticated higher-order module system (as in Standard ML), it provides modular structure with simple import commands and "hiding" specifications \end{slide} \begin{slide}{Basic Haskell: data types and classes} \slideitem{Lists as defined data types} As mentioned above, lists are pre-defined in Haskell; but they behave exactly as if defined as a recursive algebraic data type \haskon\begin{code}data List a = Nil | Cons a (List a) [1,2,3] == 1 : (2 : (3 : [])) == Cons 1 (Cons 2 (Cons 3 Nil))\end{code}\haskoff (note that the {\it constructors} Nil and Cons are spelled differently in actual Haskell code) \slideitem{The role of data constructors} Data constructors such as Nil and Cons for lists are applied like functions, but they are really only "place-holders" which build larger structures from smaller ones \slideitem{Function definition by pattern matching} We can "de-construct" constructed data either with pre-defined functions (such as {\tt head} and {\tt tail}) or by using {\bf pattern-matching}, a kind of "definition by example" \haskon\begin{code}length Nil = 0 length (Cons x y) = 1 + length y\end{code}\haskoff \slideitem{Other data type definitions} We can define our own data types in Haskell and use their constructors to build data structures or in pattern-matching to define functions on these structures \haskon\begin{code}data BTree a = Tip | Node a (BTree a) (BTree a) ins x Tip = Node x Tip Tip ins x (Node y l r) | x <= y = Node y (ins x l) r | otherwise = Node y l (ins x r)\end{code}\haskoff \slideitem{Higher-order, nested and other complex types} Haskell has a rich type system which supports powerful data structuring techniques: data types may be "higher-order" (viewed as functions from types to types) and recursion may be nested \haskon\begin{code}data GenTree s a = Branch a (s (GenTree s a)) data PerfTree a = Empty | Split a (PerfTree (a,a))\end{code}\haskoff \slideitem{Class system allows for O-O style code sharing} In addition to powerful data types, Haskell allows types to be classified into groups based on the availability of functions matching a particular interface specification (as in many O-O languages) \haskon\begin{code}class Printable a where print :: a -> String instance Printable Foo where print x = ...\end{code}\haskoff \end{slide}\nl \end{presentation} \end{document}