### CPSC 349: Haskell: 2nd lecture

-- To use Haskell on Windows, download WinHugs from here:

-- http://cvs.haskell.org/Hugs/pages/downloading-Nov2003.htm

-- Commands in the Haskell environment start with a colon:

-- If this code is in test.hs, use command ":l test.hs" to load

-- :t gives the type of something

-- :? gives a list of commands

-- Computes a factorial

fact :: Integer -> Integer

-- Int is 32 bits; Integer is unlimited.

fact 0 = 1

fact (n+1) = (n+1) * fact n

-- Gets the sum of the diagonal of a 3x3 list

-- e.g. diagonal [[1,2,3],[4,5,6],[7,8,9]] = 1+5+9 = 15

diagonal :: [[Int]] -> Int

diagonal [a,b,c] -- type decl. implies a, b, and c are lists of Int

= head a + head (tail b) + head (reverse c)

-- Tuples: complex ordered data type with unnamed elements

-- e.g. (1, 1.0, "1.0", '1', [1])

-- e.g. ("my age in years", 25)

-- 'points' compute the coordinates of a series of integer points

-- along a line, where each point is 1 unit apart horizontally

-- points 8 0 2 4

-- -> [(0,4),(1,6),(2,8),(3,10),(4,12),(5,14),(6,16),(7,18)]

points :: Int -> Int -> Int -> Int -> [(Int, Int)]

points 1 x slope intercept

= (x, x * slope + intercept) : []

points (n+1) x slope intercept

= (x, x * slope + intercept) : points n (x+1) slope intercept

-- "++": Concatenation operator: [1,2] ++ [3,4] -> [1,2,3,4]

-- ":": I don't know what it's called: [1,2] : [3,4] -> [[1,2],[3,4]]

-- You can produce functions from the built-in operators.

-- Examples:

-- (2/) is a function that divides 2 by something, so (2/) 4 -> 0.5

-- (/2) is a function that divides something by 2, so (/2) 4 -> 2.0

-- (/) is the division function: (/) 21 3 -> 7.0

-- Another example: ([1,2]++) [3,4] -> [1,2,3,4]

-- This function uses the output of another function as a "filter".

-- The filter determines whether to keep an element of the list.

myFilter :: (a -> Bool) -> [a] -> [a]

myFilter functionName [] = []

myFilter functionName (x:xs) =

if functionName x then

x : myFilter functionName xs -- Keep 'x' in the output list

else myFilter functionName xs -- Discard 'x'

-- Example:

-- myFilter (>4) [1,8,2,7,3,6,4,5] -> [8,7,6,5]

-- myFilter

## 0 Comments:

Post a Comment

<< Home