1/20
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced | Call with Kai |
|---|
No analytics yet
Send a link to your students to track their progress
what do adts let us do
define our own description data models with multiple forms
adt example
data Shape
= Circle Float
| Rectangle Float Float
| Square Float
what does pattern matching with adts allow us to define
it allows us to define how a function behaves for each possible form of the data
pattern matching with adts example
area :: Shape -> Float
area (Circle r) = pi r r
area (Rectangle w h) = w * h
area (Square s) = s * s
recursive adts
a type can be defined in terms of itself
recursive adt example
data IntList
= Empty
| Cons Int IntList
This mirrors how lists work in Haskell. The list [1,2,3] is shorthand for 1 : (2 : (3 : [])).
sumList :: IntList -> Int
sumList Empty = 0
sumList (Cons x xs) = x + sumList xs
polymorphism
allows us to write functions that work across many types
benefits of polymorphism
increases code reuse and reduces redundancy
polymorphism example
length :: [a] -> Int
identity :: a -> a
identity x = x
type classes
allow us to restrict polymorphism to types that support certain operations
common type classes
eq, ord, show
typeclass example
isEqual :: Eq a => a -> a -> Bool
isEqual x y = x == y
maxOfTwo :: Ord a => a -> a -> a
maxOfTwo x y = if x > y then x else y
combining polymorphism and type classes example
describe :: (Eq a, Show a) => a -> a -> String
describe x y =
if x == y
then "They are equal: " ++ show x
else "They are different: " ++ show x ++ " vs " ++ show y
maybe error handling
use to encode possibilities that may fail or may not return a value
maybe example
safeDiv :: Int -> Int -> Maybe Int
safeDiv _ 0 = Nothing
safeDiv x y = Just (x div y)
safeHead :: [a] -> Maybe a
safeHead [] = Nothing
safeHead (x:_) = Just x
either error handling
either allows us to return info about what went wrong
either example
safeDivMsg :: Int -> Int -> Either String Int
safeDivMsg _ 0 = Left "Division by zero!"
safeDivMsg x y = Right (x div y)
module
collection of relation functions, types, and typeclasses
define a haskell program in terms of modules
main module loads up the other modules and then uses the functions deifned in them to do something
what does show do
converts values of a type to a striing
what does read do
convert strings to values of our type