fact(0) = 1 fact(n) = n * fact(n - 1) if n > 0
fact(n) = if n == 0 then 1 else n * (fact (n - 1))
:{ fact 0 = 1 fact n = n * fact(n - 1) :}
fact(2)
fact 0 = 1 fact n | n > 0 = n * fact(n - 1)
data AppearanceResult = HomeRun | Hit Integer | Walk | Out bases_reached HomeRun = 4 bases_reached (Hit n) = n bases_reached Walk = 1 bases_reached Out = 0
bases_reached (Hit 3)
map
: apply operation to all elements in a list,
returning list
square x = x * x map square [10, 20, 30]
add_one x = x + 1 map add_one [1, 8, 22] -- but add_one is a silly function; another way to write it: add_one = (\x -> x + 1) -- test on values -- without defining a function: (\x -> x + 1) -- mapping: map (\x -> x + 1) [9, 10, 44, 12]
map (\num -> num * num * num) [5, 15, 25]
names
:
map length namesComputing the total length:
sum (map length names)
map
to compute total bases reached:
map bases_reached [Hit 2, Walk, HomeRun, Out]
let tot = (sum (map bases_reached [Hit 2, Walk, HomeRun, Out])) in (fromInteger tot) / 3
is_double (Hit 2) = True is_double _ = False length (filter is_double bases_reached)
data
to create named values even when there's
not an alternative:
data TeamMember = Player String Doublerepresenting a player with a name and some statistic such as their batting average.
newtype
keyword for such type
declarations, but we are not covering this; if you want to know more, see
this stack
overflow article.
data BST a = Node a (BST a) (BST a) | Tip inorder (Node x left right) = (inorder left) ++ [x] ++ (inorder right) inorder Tip = []
Prelude> tree = Node 10 (Node 4 Tip Tip) (Node 20 (Node 15 Tip Tip) Tip) Prelude> inorder tree [4,10,15,20]
sum
(review sum
):
sum_list [] = 0 sum_list (x : rest) = x + (sum_list rest)
map
:
map fun [] = [] map fun (value:rest) = (fun value):(map f rest)
singleton [] = False singleton (x : []) = True singleton (y : x : rest) = False
[]
case?
length
?
singleton xs = (length xs) == 1
reverse [3, 4, 8]
reverse [4]
reverse []
rev [] = [] rev a:rest = (rev rest) ++ [a]
(rev rest): a
?
[]
and (x:y)
cases
_
let
let x = a * a in x * x
let n:rest = [3, 4, 5] in n * n
where
let
, but after the expression:
fourth x = a * a where a = x * x
[x * x | x <- nums]
[x * x | x <- nums, x < 0]
lst = [9, 10, 11, 12] [[x] | x <- lst]
users = [("kelly", 8), ("john", 33), ("amy", 54), ("jane", 17), ("zoe", 80), ("jolinda", 45)] -- total years: sum [yrs | (_, yrs) <- users] -- total years of those over 20: sum [yrs | (_, yrs) <- users, yrs > 20] -- items starting with 'j' and over 20: [(name, yrs) | (name, yrs) <- users, (head name) == 'j' && yrs > 20]