CSCE 314 Lecture 4

From Notes
Jump to navigation Jump to search

« previous | Monday, September 5, 2011 | next »

Haskell Basics (cont'd)

Types

Bool
Char
Shring
List of characters
type String = [Char]
Int
Machine integer (32/64-bits)
Integer (arbitrary precision)
Arbitrary precision (slower than Ints
Float, Double
Unit
Singleton type, only one value: ()
Similar to void and null in C++

Lists

All elements must have same type:

['a', 'b', 'c'] :: [Char]
"abc" :: [Char]

-- type of the [] can be inferred from the previous list in the list
[[True, True], []] :: [[Bool]]

Lists don't have to be finite:

list = [1..]


Tuples

A finite sequence of potentially differing types for its components:

arity is number of elements within a tuple

  • Note: tuple with arity 1: Haskell ignores parentheses
('a', True) :: (Char, Bool)
("Hello", True, "World") :: ([Char], Bool, [Char])

-- the following definition will have 4 possible values
-- namely (T, T), (T, F), (F, T), (F, F)
(Bool, Bool)


Functions

Mapping from values of one type (T1) to values of another type (T2). Uses the arrow (->) operator; this operator is right associative (See #Curried Functions below).

Examples:

  • not :: Bool -> Bool
  • isAlpha :: Char -> Bool
  • toUpper :: Char -> Char
  • (&&) :: Bool -> Bool -> Bool (takes 2 boolean arguments and returns a boolean)

Usually a good idea to annotate functions with types for documentation:

square :: Int -> Int
square x = x * x

Curried Functions

Currying refers to Haskell's interpretation of functions: a function always only takes 1 argument. Anything with the illusion of more than one argument processes them one at a time, returning a partially evaluated "higher order" function that takes the next argument as input:

-- equivalent to add :: Int -> (Int -> Int)
add :: Int -> Int -> Int
add x y = x + y

add3 :: Int -> Int
add3 = add 3

z :: Int
z = add3 4

Thus function application is left-associated and has the highest precedence.

Partially applied functions can be useful... whoa!

-- The two functions do the same thing
triList :: a -> [a]
triList = replicate 3
triList a = replicate 3 a

Totality

(Total) Function maps every element in domain to an element in co-domain

Partial Function maps zero or more elements in function's domain to an element in it's co-domain, and can leave some elements undefined.


Polymorphism

The occurrence of something in several different forms

Parametrically Polymorphic functions work with many types of parameters:

-- maps a value of any type to itself
id :: a -> a
id x = x

-- computes the length of a list of any type
length :: [a] -> Int
length [] = 0
length (_:xs) = 1 + length xs

-- applies a function twice
twice :: (a -> a) -> a -> a
twice f x = f (f x)

In the code above, a is referred to as a type variable: starts with a lowercase letter and means any type.