First Haskell examples.

Start WinGHCi, in Prelude type:


    -- Haskell comments are --
    4 - 7
    4 ^ 2 + 1  -- power function ^
    6.9 + 0.1
    "This is a string"
    "This " ++ " is a string" -- string concatenation
    'a' -- a character
    length "hi"

    -- the result of the most recent experssion
    it
    
    -- Function calls
    truncate 7.3
    succ 5
    pred 5
    -- be careful with negative numbers: - is an operator, you may need parentheses
    -2 -- works
    -7.3 -- works as well
    pred -3 -- doesn't work
    pred (-3) -- works
    truncate (-7.3)
    2 * -3 -- doesn't work
    2 * (-3) -- works
    round 5.7
    round (-5.7)

    -- Booleans
    let a = 7
    let b = 5
    (a < 6) && (b > 4)
    not ((a < 6) && (b > 4))
    not True || True -- careful with precedence

    -- Comparisons
    a == 7
    a /= b
    let a = 5 -- reset a
    a /= b

    -- how to lookup docs, types
    :info truncate
    :type succ
    
    -- lists
    let mylist = [2, 5, 7]
    -- cannot mix types:
    let yourlist = [7, "hello"] -- doesn't work
    let yourlist = [7, 8.8] -- works, it's a list of reals
    -- ranges:
    [1..10]
    [1.0,1.25..2.0]
    [10,9..1]
    [1..5] ++ [7, 9]
    2:[3..5] -- cons
    ['h', 'i'] == "hi" -- strings are lists of characters
    :type "hi"
    null mylist
    null []
    head mylist
    tail mylist

    -- functions
    let factorial n = if n == 0 then 1 else n * factorial (n - 1)
    factorial 6
    map succ [1,2, 5]
    map (\x -> x * 2) mylist
    :type map
    map (\x -> x + 1) mylist
    map (\x -> x + 1.0) mylist
    map (\x -> x + 1) [8.7 6.5 2.8] -- doesn't work

    -- load and run a file
    :add first.hs
    main

The file:


fac n = if n == 0 then 1 else n * fac (n-1)

fib x
  | x < 2 = 1
  | otherwise = fib (x - 1) + fib (x - 2)

myMap func [] = []
myMap func (x:xs) = func x:(myMap func xs)

main = print (myMap (\x -> x + 2) [1..5])

CSci 4651 course web site.