Functional Programming Using Haskell

  • View
    69

  • Download
    4

Embed Size (px)

DESCRIPTION

Functional Programming Using Haskell. Dan Vasicek 2010 – 03 – 21. Functional Programming in Haskell. Haskell Information Sources Fundamental concepts Functional Programming Sessions, modules, & scripts Polymorphic types Order of evaluation Patterns Lazy evaluation Side Effects. - PowerPoint PPT Presentation

Text of Functional Programming Using Haskell

  • Functional Programming Using HaskellDan Vasicek2010 03 21

  • Functional Programming in HaskellHaskell Information SourcesFundamental conceptsFunctional ProgrammingSessions, modules, & scriptsPolymorphic typesOrder of evaluationPatternsLazy evaluationSide Effects Fundamental Data typesBoolianNumbersCharacters Compound data typesTuplesListsUser Defined TypesEnumerations EfficiencyEvaluation orderLazy EvaluationSpace MonadsExamples

  • Sources of InformationBook - Introduction to Functional Programming Using Haskell, Richard Bird, Pearson Education Limited, England, Prentice Hall Europe 1998Tutorial - http://www.cs.utah.edu/~hal/docs/daume02yaht.pdf For writing real production code see:http://haskell.org/haskellwiki/How_to_write_a_Haskell_program

  • Three Haskell SystemsHUGS Haskell Users Gofer SystemInterpreter onlyhttp://www.haskell.org/hugs Faster than ghc GHC Glasgow Haskell CompilerBoth interpreter and compilerSlower , more complex, and bigger than hugs and nhc NHC - Nearly a Haskell CompilerComplier onlyhttp://www.haskell.org/nhc98/download.html

  • Functional ProgrammingA functional program is a function that solves a problemThat function may involve several subsidiary functions and is described in a notation that obeys normal mathematical principlesThe result of the function is the solution of the problem and is disjoint from the input to the functionAs in mathematics, once a function is proven correct, changes in the environment will not invalidate your proofFunctions can be passed as arguments and are first classFunctions do not change the global stateSingle assignment. Once a variable gets a value, it never changes.

  • Functional Programming in CProhibit the use of pointers?Not likely!Careful use of pointersNo modification of input parametersAll output is clearly separated from the inputOutput = function_name(input)Subroutine_name (input; output)

  • Fundamental Concepts of HaskellPolymorphic Static typeslength list The list can have elements of any type. So, length is polymorphic. It can be applied to lists of characters, numbers, tuples, lists, length [] = 0length (x:xs) = 1+ length xs Where [] is a pattern that means the empty listAnd x:xs is a pattern that means x is the first element of the input list and xs is the rest of the list (: is the cons operator)Called pattern matching. And pattern matching is an important component of Haskell (more later)

  • Examples of Polymorphismhead::[a]->a head(x:xs)=x tail::[a]->[a] tail(x:xs)=xsBoth fail if presented with an empty listBoth work for lists of anything, even lists of empty lists and are PolymorphicExamples of the Hindley-Milner type system

  • Order of EvaluationOrder of evaluation (simplification, or reduction) is not specified in a functional programDefine: sq x = x*xsq(3+4) could be simplified as sq(7) 7*7 49(3+4)*(3+4) 7*(3+4) 7*749Both orders produce the same resultThe independence of the result from the order is a characteristic feature functional programsThe OS is free to choose the best order

  • Lazy Evaluationlet three x = 3let infinity = infinity +1Now simplify the expression three infinitySimplification of infinity first givesThree(infinity +1 +1 +1 and so on) which does not terminateSimplification of three first, three infinity = 3the expression terminates in one stepSome simplification orders may terminate while others do notIn GHCi three infinity =3In general, some simplification orders will be more efficient than others

  • Lazy EvaluationGuarantees termination whenever termination is possibleAllows the OS to choose an efficient evaluation order

  • Side EffectsA side effect is essentially something that happens in the course of executing a function that is not related to the output produced by that function.A pure function simply returns a valueA pure function has no internal stateA pure function cannot modify the input dataGiven the same arguments a pure function will always produce the same resultIn GHCi values may be displayed by the interactive environmentMonadic programming allows functional programs to mimic imperative programsMonads provide a way to execute Commands and display values

  • MonadsHaskell uses monads to isolate all impure (not functional) computations from the rest of the program and perform them in the safe wayThe execution order of a functional program is entirely determined by the operating system. And this applies to the order of execution of I/O as wellThus, the order of I/O can not be preserved by a functional program

  • Example of Scrambled I/O OrderThus, the order of I/O can not be preserved by a functional programSuppose that your functional program wrote the words in the following order:be preserved a functional program the order of I/O can not by Thus,

  • Imperative Constructs are NOT Functionalx=x+1 is not allowed!All ghci commands are imperative. The interactive environment is imperativehttp://www.haskell.org/haskellwiki/Functional_programminghttp://www.haskell.org/all_about_monads/html/class.html

  • Haskell Fundamental Data TypesBool: True or False Char: a , '\n', '\x05e0, \122 a newline zNumber: 12.718

  • Compound Data typesTuples(a, Daniel, 3.14159) is valid(1, map) is a valid tuple. But you will have to define an I/O Monad to Show it.The functions for extracting the first and second element of a pair are defined in the standard Haskell environmentfst(x,y) = xsnd(x,y) = yfst(1,2,3) is not defined in the standard environment

  • ListsLists a list is enclosed in square bracketsThe empty list is []The cons operator is :1:2:3:[] is [1,2,3]Daniel is D:a:n:i:e:l:[] =[D,a,n,i,e,l]D:an = DanAll elements of a list must be of the same type[[1,2],[1]] is a valid list

  • Comments in Haskell CodeSingle line comments are preceded by ``--'' and continue to the end of the line. For example: suc n = n + 1 -- this is a successor functionMultiline and nested comments begin with {- and end with -}. Thus {- can be used to inactivate a block of code -}

  • Literate Programming A literate code file is a file with suffix .lhs instead of .hs (Literate Haskell)Two styles for literate code:LaTeX Style : \begin{code} \end{code}Bird Style: prefix code lines with the > characterCompiler flags allow for reconfiguration of the literate style

  • Example: LaTeX Literate StyleHere is a simple example of a literate script for defining the quicksort function:\begin{code} tsort [] = [] tsort (x:xs) = tsort [y | y
  • Example: Richard Bird Literate StyleIn Bird-style a blank line is required before the code >fact :: Integer -> Integer > fact 0 = 1 > fact n = n * fact (n-1)

    And a blank line is required after the code as well

  • Emacs Supports a Multi Mode Display One style for LaTeXAnd a second style for Haskellhttp://www.haskell.org/haskellwiki/Literate_programming#Haskell_and_literate_programming

  • Literate Programming in VIMhttp://www.haskell.org/haskellwiki/Literate_programming/Vim

  • Quick Sort Algorithmqsort [] = []qsort ( x:xs) = qsort (filter (< x) xs) ++ qsort (filter ( >= x) xs)

    Inefficient! Calls filter twice for xsCan use (length (x:xs))2memory

  • More Efficient quicksortqsort [] = []qsort x:xs = qsort ys ++ [x] ++ qsort zs where (ys, zs) = partition (< x) xs

    Avoids filtering xs twiceStill can use n2 memory!Notice that the < is necessary in the comparison to preserve the original order of identical elements

  • User Defined TypesEnumerated Typesdata Typename = Type1 | Type2| Type3

  • Example of Enumerated Typemodule Colorwheredata Color = Red | Orange | Yellow| Green| Blue| Purple | White | Black

    colorToRGB Red = (255,0,0)colorToRGB Orange = (255,128,0)colorToRGB Yellow = (255,255,0)colorToRGB Green = (0,255,0)colorToRGB Blue = (0,0,255)colorToRGB Purple = (255,0,255)colorToRGB White = (255,255,255)colorToRGB Black = (0,0,0)

  • Example of Enumerated TypescolorToRGB Red returns the value: (255,0,0)Red == Blue fails because == is not defined for type ColorcolorToRGB Red == colorToRGB Blue Returns the value False

  • User Defined TypesUser defined data types are done via a ``data'' declaration having the general form: data T u1 ... un = C1 t11 ... t1k1 | ... | Cn tn1 ... Tnknwhere T is a type constructor; the ui are type variables; the Ci are (data) constructors; and the tij are the constituent types (possibly containing some ui). The presence of the ui implies that the type is polymorphic --- it may be instantiated by substituting specific types for the ui

  • User Defined Typesdata Bool = True | False Bool is the type constructorTrue and False are the data constructorsdata Color = Red | Green | Blue | Indigo data Point a = Pt a a a on the lhs is a type variabledata Tree a = Branch (Tree a) (Tree a) | Leaf aa is a constituent type on the rhs

  • Type SynonymsGeneral Definition Unknown (examples only)type String = [Char] type Person = (Name, Address) type Name = String data Address = None | Addr String

  • Pythagorian Triadsmodule PythagorianTriadswhere triples :: Int -> [(Int, Int, Int)]triples n = [(x, y, z) | x
  • More Efficient Version module PythagorianTriadswhere triples :: Int -> [(Int, Int, Int)]triples n = [(x, y, z) | x
  • Overloading Operators class Eq where (==) :: -> -> Bool

    instance Eq Color where (x == y) = ((colorToRGB x) == (colorToRGB y))

    Unfortunately, this does not compile!

  • Unicode in HaskellHaskell 98 sp