using haskell

Download Using Haskell

Post on 31-Jan-2016

48 views

Category:

Documents

0 download

Embed Size (px)

DESCRIPTION

Using Haskell. Dan Vasicek 2010 02 21. What is Haskell? (Theoretical Aspects). Haskell is a computer programming language In particular, it is a polymorphically statically typed , lazy , purely functional language, quite different from most other programming languages - PowerPoint PPT Presentation

TRANSCRIPT

  • Using HaskellDan Vasicek2010 02 21

  • What is Haskell? (Theoretical Aspects)Haskell is a computer programming language In particular, it is a polymorphically statically typed, lazy, purely functional language, quite different from most other programming languages The language is named for Haskell Brooks Curry, whose work in mathematical logic serves as a foundation for functional languages Haskell is based on the lambda calculus, hence the symbol, , is used as part of the Haskell logo

  • What is Haskell? (Practical Aspects)Two commands for your command line environmentghc Glasgow Haskell Compiler: produces executable code from Haskell sourceghci Glasgow Haskell Command line Interpreter:An environment for the execution of Haskell commandsSpecial commands for manipulating, & querying the environmentDebugging commandsForeign language (e.g. C++) interface

  • Why Consider Haskell?Produces concise, provably correct codeShort code development timeInteractive and compilableBuilt-in Concurrency and ParallelismA high level modern programming language that is a result of 20 years of developmentSupported by a large library of packaged modulesSupplied with debuggers and profilersFreely available (Open source, $0, complete development package)

  • Installation of Glasgow Haskell Platform Download most recent versionStable versions from: http://hackage.haskell.org/platform Windows version is 54 Megabytes (Feb 1, 2010)Mac OS X is 106 MegabytesSource tarball is 1.28 MegabytesLinux X86 & X86-64 ~ 72 Megabyteshttp://haskell.org/ghc/download_ghc_6_10_4.html#x86linux Other Haskell Compilers - e.g. http://repetae.net/computer/jhc/ (Efficient)

  • Example GHCi Session - Strings

  • Glasgow Haskell PlatformGHC 6.10.4 - The state-of-the-art optimzing compiler for Haskell.GHCi 6.10.4 - A bytecode interpreter and interactive environment for HaskellThe GHCi debugger - An interactive, imperative-style debugger for HaskellThe GHC parallel runtime - a multicore language runtime, featuring lightweight threads, thread sparks, affinity control, and a parallel garbage collectorThe Happy parser generator - Happy 1.18.4, a yacc-like parser generator for HaskellThe Alex lexer generator - Alex 2.3.1, a lex-like lexer generator for HaskellThe Haddock Documentation tool - generator Haddock 2.4.2The Cabal package distribution tool - cabal-install 0.6.2, download and install new Haskell packages from HackageThe hsc2hs foreign language binding tool - a preprocessor for binding Haskell to C - (e.g. Access to HDF5, FITS, data)Unicode built-in

  • Editor Syntax highlighting and formatting support Emacs Haskell ModeVIM Superior Haskell Interaction Mode (SHIM)

  • List of Available Packageshttp://hackage.haskell.org/packages/hackage.htmlCurrently there are 1800 Haskell Packages availableCompare to 9033 Python packages availableSee the appendix of these slides for a listing of some Haskell Packages

  • Haskell Syntax Some Referenceshttp://www.haskell.org/onlinereport/syntax-iso.html - general syntax descriptionhttp://www.haskell.org/onlinereport/standard-prelude.html - standard functionshttp://www.cs.chalmers.se/Cs/Grundutb/Kurser/d1pt/d1pta/ListDoc - Standard list functions

  • Simple SyntaxStrongly TypedSimple arithmeticArbitrary precision integersString manipulationList manipulation such as sorting

  • Positionally Sensitive NotationThe next character following any of the keywords where, let, or of is what determines the starting column for the declarations in the where, let, or case expression being writtenBe sure that the starting column is further to the right than the starting column associated with the immediately surrounding clause (otherwise it would be ambiguous). The "termination" of a declaration happens when something appears at or to the left of the starting column associated with that binding form. (Haskell observes the convention that tabs count as 8 blanks; thus care must be taken when using an editor which may observe some other convention.)

  • Type Signatures (::)5::Integer'a'::Charabc :: [Char] (is a list of characters)(+1)::Integer->Integer {e.g.(+1) 1 =2)}[1,2,3]::[Integer]- List of Integers('b',4)::(Char,Integer) - Pair

  • Simple Arithmetic Using GHCi Prelude> 3+710Prelude> 2*816Prelude> 100/254.0

  • Arbitrary Precision Integers in GHCi

    Prelude> 2^200160693804425899027554196209234116260252220299378279283530137661 digits (Same result as Mathematica)Prelude> 1/30.3333333333333333Sixteen significant figureslog(10^300)/log(10) = 299.9999999999994

  • List Operationsabc is [a, b, c]abc!!0 is a list item abc!!2 is c ab ++ cd is abcd Concatinationhead abc is a cartail abc is bc cdrtake 2 abc is abtake 1 abc is a is [a]drop 1 abc is bcreverse(abcdefg) is gfedcbalength(abc) is 3

  • Shorthand for lists of integers[1..4] [1,2,3,4][1,3..10] [1,3,5,7,9][1,3..] [1,3,5,7,9,11, infinite sequence

  • More List Operationsmap (/2) [1, 2, 3] is [.5, 1.0, 1.5]map sin [1, 2, 3] is [.84, .91, .14]foldr (+) 0 [1, 2, 3, 4] is 10 (n=1n=4n)foldr (*) 0 [1..4] is 0foldr (*) 1 [1,2,3,4] is 24 (4!)filter (4
  • Define a simple functionlet sq(x) = x*xsq(9)81sq 525sq is a function that is no more special than * or + (more on the next slide)

  • Redefine basic operationslet x + y = x*yThen 4+5=20

  • Type and definition of mapusing patternsmap ::(a->b)->[a]->[b] mapf[] =[] mapf(x:xs) =fx:mapfxs

    map f :: [a] [b]

  • GHCi CommandsThe : operator tells GHCi to expect a command:? Or : Gives a summary of : commands:browse will list the current environment:browse will list the contents of a module:show will display the syntax of the show command:show bindings will display current bindings:! Cmd pass Cmd to the shellE.g. :!dir will display the current directory (in DOS)

  • Example of the :show command:show bindingssq :: (Num a) = > aa = _Which says that sq is a function of numbers that takes a number, returns a number, and prints the value of the number

  • Creating a Haskell Script:set editor "C:\Program Files\Vim\vim72\gvim.exeSets the editor to be gvim:edit fac.hsCreates a file called fac.hs containingfac(0) = 1fac(n) = n*fac(n-1):load fac Compiles and loads fac.hs into the environment

  • Executing fac scriptfac(3)6fac(10)2628800The function fac is called primitive recursive

  • Validation of fac by inductionfac(0)=1fac(1) =1fac(2)=2Fac(100) is a big number and is probably correct

  • Ackermanns FunctionIs not primitive recursiveDefinition ------------------------------------------ack(0,n) = n+1ack(m+1, 0) = ack(m,1)ack(m,n) = ack(m-1,ack(m,n-1))Program Validation-----------------------------ack(0,0) = 1ack(2,0)= 5 ack(3,3) = 61

  • Inquire about the environment:show modulesMain ( fac.hs, interpreted)

  • GHCi ConfigurationWhen GHCi starts it executes config files in order:1. .ghci file2. appdata/ghc/ghci.conf where appdata is C:/Documents and Settings/user/Application Data (on MS Win)$HOME/.ghc/ghci.conf (on Unix)3. $HOME/ghci.conf

  • Creating a GHCi configuration file:edit .ghciType a configuration script for example::set editor "C:\Program Files\Vim\vim72\gvim.exeSave this file in the default GHCi directory To find the default directory see the results of the :!dir command on windows:!pwd on LinuxNow gvim will be the default editor instead of Notepad

  • Begin Functional Programming SegmentFundamental conceptsFunctional ProgrammingSessions and scriptsPolymorphic typesOrder of evaluationPatternsLazy evaluationSide EffectsSimple data typesNumbersListsTreesEfficiencyEvaluation orderLazy EvaluationSpace Abstract Data TypesInfinite listsMonadsParsingExamples

  • 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 function

  • Fundamental ConceptsPolymorphic 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 listPattern matching is an important component of Haskell

  • Polymorphismhead::[a]->ahead(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 programsq(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 programs

  • Lazy EvaluationLet three x = 3Let infinity = infinity +1Now simplify the expression three infinityIf we choose to simplify infinity first we getThree(infinity +1 +1 +1 and so on) which does not terminateIf we choose to simplify three first, three infinity = 3the expression terminates in one stepSome simplification orders may terminate while others do notIn GHCi three infinity =3

  • Lazy EvaluationGuarantees termination w