Thursday, October 13, 2005

Haskell - lecture 6

-- I can't figure out what's going on here.
test1 = (\y -> (-) y 1)
-- test2 = (\y -> (-) y (\x -> x)) -- won't compile
test2 z = (\y -> (-) y (\x -> x)) z
test3 z = \y -> (-) y (\x -> x) z
test2b a b = (\y -> (-) y (\x -> x)) a b
test3b a b = \y -> (-) y (\x -> x) a b

-- Prof implied that Haskell has no random-access arrays;
-- e.g. efficient hashtables cannot be created.

-- Data types in Haskell
-- Lists
-- [l] ++ [3,4], a : b
-- Tuple
-- (0, "abc", 'd', 5.0)
-- Enumerated:
-- data Weekday = Sun | Mon | Tue | Wed | Thu | Fri | Sat
-- Recursively defined types
-- data Tree a = Leaf a | Node (Tree a) (Tree a)
-- Lambda abstractions
-- List comprehensions

-- Declaration order doesn't usually matter, but module imports
-- must come first? Also, function signatures' patterns are
-- checked/matched in the order they appear, every time a
-- function is called. For example, out of the four functions below,
-- the first one is always regardless of the arguments. Even so,
-- note that the arguments must be lists, because in Haskell, all
-- functions with the same name share the same data type
-- signature. Try changing the order to see what happens.
orderTest a b = "a b"
orderTest a [] = "a []"
orderTest [] [] = "[] []"
orderTest (x:xs) (y:ys) = "(x:xs) (y:ys)"

-- Control Constructs
-- Patterns: pattern matching on function signatures is implicit flow control
-- Guards
-- "Where" - creates temporary local variables; example below
-- List comprehensions

-- Finds the roots of ax^2 + bx + c
-- Example: roots 1 5 6 -> (-2.0,-3.0)
roots a b c =
if d < 0 then error "imaginary" else (x1, x2)
where
x1 = (-b + (sqrt d)) / twoa
x2 = (-b - (sqrt d)) / twoa
d = b*b - 4*a*c
twoa = 2*a

0 Comments:

Post a Comment

<< Home