FP in Scala and Recursion in FP Flashcards
write a sum function in Scala
def sum (xs : List[Int]) : Int = xs match { case Nil => 0 case x :: ys => x + sum(ys) } }
define the type of length in Scala using a generic type
length :: [T] (xs : List [T]) Int
what type of list is also possible in Scala?
heterogenous lists
What is list comprehension called in Scala?
sequence comprehension
Write a quicksort function in Scala
def qsort ( xs : List[Int]) : List[Int] = xs match { case Nil => Nil case x :: ys => qsort(for(i x) yield j)
what is the basic looping mechanism in fp?
recursion
define zip with recursion
zip :: [a] -> [b] -> [(a, b)]
zip [] _ = []
zip _ [] = []
zip (x : xs) (y : ys) = (x, y) : zip xs ys
define qsort with recursion
qsort :: [Int] -> [Int] qsort [] = [] qsort(x : xs) = qsort smaller ++ [x] ++ qsort larger where smaller = [a | a x]
5 steps for writing recursions
- define the type
- enumerate the cases
- define the base cases
- define the step cases
5 generalise / simplify
write a recursive sum in Scala
def sum (xs : List[Int]) : Int = xs match { case Nil => 0 case x :: ys => x + sum(ys) }
sum: (xs : List[Int]) Int
what are the 2 styles of typing?
church style and curry style
Describe Church-style typing
\x:A.b
with domain’s type label (A)
Describe Curry-style typing
\x.b
without somain’s type label
describe typing in Scala
we need the type label of the domain and range
\x:A.(b:B)
what is a μ-recursive function?
a general recursive function.
partial functions that take finite tuples of Nat numbers and return one Nat number