# Haskell. 2 GHC and HUGS Haskell 98 is the current version of Haskell GHC (Glasgow Haskell Compiler, version 7.4.1) is the version of Haskell I am using

Post on 13-Jan-2016

217 views

Embed Size (px)

TRANSCRIPT

Haskell

*

GHC and HUGSHaskell 98 is the current version of Haskell

GHC (Glasgow Haskell Compiler, version 7.4.1) is the version of Haskell I am usingGHCi is the REPLJust enter ghci at the command line

HUGS is also a popular versionAs far as the language is concerned, there are no differences between the two that concern us.

*

Using HaskellYou can do arithmetic at the prompt:Main> 2 + 2 4 You can call functions at the prompt:Main> sqrt 10 3.16228The GHCi documentation says that functions must be loaded from a file:Main> :l "test.hs" Reading file "test.hs": But you can define them in GHCi with letlet double x = 2 * x*

Lexical issuesHaskell is case-sensitiveVariables begin with a lowercase letterType names begin with an uppercase letterIndentation matters (braces and semicolons can also be used, but its not common)There are two types of comments: -- (two hyphens) to end of line{- multi-line {- these may be nested -} -}*

SemanticsThe best way to think of a Haskell program is as a single mathematical expressionIn Haskell you do not have a sequence of statements, each of which makes some changes in the state of the programInstead you evaluate an expression, which can call functionsHaskell is a functional programming language*

Functional Programming (FP)In FP,Functions are first-class objects. That is, they are values, just like other objects are values, and can be treated as suchFunctions can be assigned to variables, passed as parameters to higher-order functions, returned as results of functionsThere is some way to write function literalsFunctions should only transform their inputs into their outputsA function should have no side effectsIt should not do any input/outputIt should not change any state (any external data)Given the same inputs, a function should produce the same outputs, every time--it is deterministicIf a function is side-effect free and deterministic, it has referential transparencyall calls to the function could be replaced in the program text by the result of the functionBut we need random numbers, date and time, input and output, etc.*

TypesHaskell is strongly typedbut type declarations are seldom needed, because Haskell does type inferencingPrimitive types: Int, Float, Char, BoolLists: [2, 3, 5, 7, 11]All list elements must be the same typeTuples: (1, 5, True, 'a')Tuple elements may be different types*

Bool OperatorsBool values are True and FalseNotice how these are capitalizedAnd is infix &&Or is infix ||Not is prefix notFunctions have typesNot is type Bool -> BoolAnd and Or are type Bool -> Bool -> Bool*

Arithmetic on Integers+ - * / ^ are infix operatorsAdd, subtract, and multiply are type (Num a) => a -> a -> aDivide is type (Fractional a) => a -> a -> a Exponentiation is type (Num a, Integral b) => a -> b -> aeven and odd are prefix operatorsThey have type (Integral a) => a -> Booldiv, quot, gcd, lcm are also prefixThey have type (Integral a) => a -> a -> a*

Floating-Point Arithmetic+ - * / ^ are infix operators, with the types specified previouslysin, cos, tan, log, exp, sqrt, log, log10These are prefix operators, with type (Floating a) => a -> a piType Float truncateType (RealFrac a, Integral b) => a -> b*

Operations on CharsThese operations require import Data.Charord is Char -> Intchr is Int -> CharisPrint, isSpace, isAscii, isControl, isUpper, isLower, isAlpha, isDigit, isAlphaNum are all Char-> BoolA string is just a list of Char, that is, [Char]"abc" == ['a', 'b', 'c'] *

Polymorphic Functions== /=Equality and inequality tests are type (Eq a) => a -> a -> Bool< = >These comparisons are type (Ord a) => a -> a -> Boolshow will convert almost anything to a stringAny operator can be used as infix or prefix(+) 2 2 is the same as 2 + 2100 `mod` 7 is the same as mod 100 7

*

Operations on Lists I*

head

[a] -> a

First element

tail

[a] -> [a]

All but first

:

a -> [a] -> [a]

Add as first

last

[a] -> a

Last element

init

[a] -> [a]

All but last

reverse

[a] -> [a]

Reverse

Operations on Lists II*

!!

[a] -> Int -> a

Index (from 0)

take

Int -> [a] -> [a]

First n elements

drop

Int -> [a] -> [a]

Remove first n

nub

[a] -> [a]

Remove duplicates

length

[a] -> Int

Number of elements

Operations on Lists III*

elem, notElem

a -> [a] -> Bool

Membership

concat

[[a]] -> [a]

Concatenate lists

Operations on Tuplesand nothing else, really.*

fst

(a, b) -> a

First of two elements

snd

(a, b) -> b

Second of two elements

Lazy EvaluationNo value is ever computed until it is neededLazy evaluation allows infinite listsArithmetic over infinite lists is supportedSome operations must be avoided, for example, finding the last element of an infinite list*

Finite and Infinite Lists*

[a..b]

All values a to b

[1..4] =[1, 2, 3, 4]

[a..]

All values a and larger

[1..] = positive integers

[a, b..c]

a step (b-a) up to c

[1, 3..10] = [1,3,5,7,9]

[a, b..]

a step (b-a)

[1, 3..] = positive odd integers

- List Comprehensions I[ expression_using_x | x
- List Comprehensions II[ expression_using_x_and_y | x
- List Comprehensions III[ expression_using_x | generator_for_x, test_on_x] take 5 [x*x | x
- List Comprehensions IV[x+y | x
Simple FunctionsFunctions are defined using =avg x y = (x + y) / 2:type or :t tells you the type:t avg(Fractional a) => a -> a -> a *

Anonymous FunctionsAnonymous functions are used often in Haskell, usually enclosed in parentheses\x y -> (x + y) / 2the \ is pronounced lambdaIts just a convenient way to type the x and y are the formal parametersFunctions are first-class objects and can be assignedavg = \x y -> (x + y) / 2*

Haskell Brooks CurryHaskell Brooks Curry (September 12, 1900 September 1, 1982) Developed Combinatorial Logic, the basis for Haskell and many other functional languages*

CurryingCurrying is a technique named after the logician Haskell CurryCurrying absorbs an argument into a function, returning a new function that takes one fewer argumentf a b = (f a) b, where (f a) is a curried functionFor example, if avg = \x y -> (x + y) / 2 then (avg 6) returns a functionThis new function takes one argument (y) and returns the average of that argument with 6Consequently, we can say that in Haskell, every function takes exactly one argument*

Currying exampleAnd, &&, has the type Bool -> Bool -> Boolx && y can be written as (&&) x yIf x is True, (&&)x is a function that returns the value of yIf x is False, (&&)x is a function that returns FalseIt accepts y as a parameter, but doesnt use its value

*

Slicingnegative = (< 0)Main> negative 5FalseMain> negative (-3)TrueMain> :type negativenegative :: Integer -> BoolMain> *

Factorial Ifact n = if n == 0 then 1 else n * fact (n - 1)This is an extremely conventional definition.*

Factorial IIfact n | n == 0 = 1 | otherwise = n * fact (n - 1)Each | indicates a guard.Notice where the equal signs are.*

Factorial IIIfact n = case n of 0 -> 1 n -> n * fact (n - 1)This is essentially the same as the last definition.*

Factorial IVYou can introduce new variables with

let declarations in expressionfact n | n == 0 = 1 | otherwise = let m = n - 1 in n * fact m*

Factorial VYou can also introduce new variables with

expression where declarationsfact n | n == 0 = 1 | otherwise = n * fact m where m = n - 1*

The End*

******************************

Recommended