Chapter 8 in Learn You a Haskell ... (Algebraic data types intro).
type
: Does not really define a new type, just provides
a new name for an existing type (type synonym)
type
Name = Existing_type
data
function and define
value constructors (constructor functions for the new
type)
data Bool = False | True data DayOfWeek = Sunday | Monday | Tuesday | Wednesday | Thursday | Friday | Saturday data Point = Point Float Float deriving (Show) data Shape = Circle Point Float | Rectangle Point Point deriving (Show) area :: Shape -> Float area (Circle (Point x y) r) = pi * r^2 area (Rectangle (Point ulX ulY) (Point lrX lrY)) = (lrX - ulX) * (lrY - ulY) data IntBinTree Int = Leaf Int | Branch Int (IntBinTree Int) (IntBinTree Int) deriving (Show) data BinTree aType = Leaf aType | Branch aType (BinTree aType) (BinTree aType) deriving (Show) fringe :: BinTree aType -> [aType] fringe (Leaf x) = [x] fringe (Branch x left right) = fringe left ++ fringe rightExpression that builds a tree:
Branch "Lauren" (Branch "Alyce" (Leaf "John") (Leaf "Jan")) (Branch "JB" (Leaf "Jack") (Leaf "Mary"))
Also in Chapter 8 in Learn You a Haskell ... (Typeclasses 102).
class Eq alpha where (==) :: alpha -> alpha -> Bool (/=) :: alpha -> alpha -> Bool x == y = not ( x /= y ) x /= y = not ( x == y )
instance Eq Bool where (x == y) = (x && y) || (not x && not y) (x /= y) = not (x == y)
deleteFirstMatching:: (Eq a) => [a] -> a -> [a] deleteFirstMatching [ ] _ = [ ] deleteFirstMatching (h : rest) item | h == item = rest | otherwise = h : (deleteFirstMatching rest item)Since we're using
==
in a guard, the type variable
(a
) must represent a type that is an instance of
Eq
.