CSCE 314 Lecture 6

From Notes
Jump to navigation Jump to search

« previous | Friday, September 9, 2011 | next »


More Haskell!

Yaay!

Defining Functions

Guards

conditional code for given arguments (note: otherwise = True in Prelude)

max x y
  | x <= y    = y
  | otherwise = x

Pattern Matching

Syntactic sugar used to assign certain parts of an argument expression into variables or match a literal/constant value:

-- definition of AND operator using literal pattern matching
(^) :: Bool -> Bool -> Bool
True ^ True = True
True ^ False = False
False ^ True = False
False ^ False = False

-- Same function using a variable (also executes faster)
(^) :: Bool -> Bool -> Bool
True ^ b  = b
False ^ _ = False

The "_" variable matches anything, but will never be used

The same variable (save for _) can never be used in the same pattern match expression

Patterns can be arbitrarily deep:

-- a list of at least 5 elements
f (a:b:c:d:e:fs) = a:b:c:d:e:[]
-- the second component of the second element in a list of 2-tuples
g (_:(_, x):_)

Even arithmetic expressions (but one of the vars must be a constant)

pred :: Int -> Int
pred 0 = 0
pred (n + 1) = n

Naming subparts of pattern or entire pattern:

dupOrRem whole@(x:tail@(y:_))
  | x == y    = x:whole
  | otherwise = tail

> dupOrRem [1,1]
[1,1,1]
> dupOrRem [1,2]
[2]

Case Expressions

Haskell's version of a switch ... case ... statement:

take m ys = case (m, ys) of
    (n, _) | n <= 0 -> []
    (_, [])         -> []
    (n, x:xs)       -> x : take (m-1) xs

Lambda Functions

unnamed functions that can be used in-place:

\x -> x + x
\x y -> x >= y || x < 2*y

> map (\x -> x + x) [1,2,3]
[2,4,6]