






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
A set of lecture notes from a computer science course (cpsc 326) held in spring 2013. The notes cover the topics of algebraic data types and user-defined parametric types in haskell. Comparisons between haskell and c/c++, pattern matching with algebraic data types, and the use of maybe type instead of error handling.
Typology: Study notes
1 / 12
This page cannot be seen from the preview
Don't miss anything!







Today ...
-- Haskell // C/C++ data Book = Book struct Book { Integer int id; String char* name; [String] char** authors; };
Q: What are the differences?
-- Haskell // C/C++ data Book = Red enum Color { | Blue RED, | Green BLUE, deriving (Show, Eq) GREEN };
Q: What are the differences?
Can use data constructors and fields with pattern matching
bookID (Book id _ _) = id bookTitle (Book _ title _) = title bookAuthros (Book _ title _) = authors
We can get rid of the “boilerplate”
*Main> bookTitle b "Neuromancer"
*Main> :type bookTitle bookTitle :: Book -> Title
*Main> let b2 = Book { bookTitle = "The Stranger", bookID = 45, bookAuthors = ["Camus"] }
*Main> bookTitle b "Neuromancer"
Prelude> m Just "something"
Prelude> :type m m2 :: Maybe [Char]
myDiv x y | y == 0 = Nothing | otherwise = Just (x / y)
*Main> :type myDiv (Fractional a) => a -> a -> Maybe a
*Main> myDiv 1 0 Nothing
*Main> myDiv 1 1 Just 1.
The standard “error” function
error :: String -> a
Why does error return any type?
Using error to return the second element of a list
sndL :: [a] -> a sndL (:x:) = x sndL _ = error "List too short!"
*Main> sndL [] *** Exception: List too short!
*Main> sndL [1] *** Exception: List too short!
*Main> sndL [1,2] 2
Representing a binary search tree (BST)
data Tree a = Node a (Tree a) (Tree a) | Nil deriving (Show, Eq)
Q: Create the following trees ...
Implementing a BST
isEmpty :: Tree a -> Bool isEmpty Nil = True isEmpty _ = False
size :: (Num b) => Tree a -> b size Nil = 0 size (Node _ l r) = 1 + (size l) + (size r)
height :: (Num b) => Tree a -> b height Nil = 0 height (Node _ l r) = 1 + max (height 1) (height r)
insert :: (Ord a) => a -> Tree a -> Tree a insert x Nil = Node x Nil Nil insert x (Node y l r ) | x < y = Node y (insert x l) r | otherwise = Node y l (insert x r)
find :: (Ord a) => a -> Tree a -> Bool find x Nil = False find x (Node y l r) | x == y = True | x < y = find x l | otherwise = find x r