CSCE 314 Lecture 3

From Notes
Jump to navigation Jump to search

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


Haskell Basics

Haskell is a pure functional language

  • Statically typed through type inference
    • Bool, Int, Integer (arbitrary precision), etc.
    • Sometimes code must be annotated with types
  • indentation-sensitive
    • Less indentation: "close brace inserted"
    • More indentation: "still part of same definition"
    • Equal indentation: "semicolon inserted"
  • Terse, expressive syntax (shorter programs)
  • Evaluated outside-in, then arguments eval'ed left-to-right
    • "Call-by-need" anything not needed is not evaluated or executed
    • Memoization: Haskell remembers the evaluation value of a function.

Normal Scripts

Extension: *.hs

Comments explicitly labeled with --

-- myscript.hs: a few simple functions
-- add computes the sum of two numbers

add x y = x + y

Literal Scripts

Extension: *.lhs

myscript.lhs: a few simple functions
add computes the sum of two numbers

> add x y = x + y

Example Function: Quicksort

"A sorted list is all of the sorted elements less than the first element, the first element, and all of the sorted elements greater than the first element."

f []     = []
f (x:xs) = f ys ++ [x] ++ f zs
    where
        ys = filter (<=x) xs
        zs = filter (>x) xs