Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Monday, January 21, 2008

Scala exercises

Though I would post up some of the exercises I have been working on to help me understand functional programming in Scala. These exercies were given to me by tony Morris to help me get my head around function programing.

1. Create a flat map using a foldRight
solution:
def myFlatMap[I, J](l : List[I], f: I => List[J] ) : List[J] = {
l.foldRight(Nil : List[J])((a,b) => (f(a) ::: b ) )
}

2. Create concatenation for a cons list (:::) using a foldRight
solution:
def append[X](xs: List[X], ys: List[X]): List[X] = {
xs.foldRight(ys)(_ :: _)
}

3. Create concatenation using matcher and recursion
solution:
def append2[X](xs: List[X], ys: List[X]): List[X] = xs match {
case Nil => ys
case x :: xs => {
x :: append2(xs, ys)
}
}

4. Find the max int in a list
solution :
def getMaxInt(xs : List[int]) : int = xs match {
case Nil => error("error")
case x :: xs =>
xs.foldLeft(x)((b,a) => if ( a > b) a else b )
}

Sunday, January 20, 2008

Programming Terms

While learning scala I needed to know some terms to understand what is going on. So here is a list of terms I needed to understand with an example of what they are in the languages I understand and a link to the definition.

First class object: In java this is an object
wikipedia link

First class functions: In ruby this a a block/proc. First class Functions can be created at runtime stored in a variable and passed into other methods.
wikipedia link

Higher order function: In ruby this is a function that take a block.
wikipedia link

Currying: transforming a function that takes multiple arguments into a function that takes 1 arguement. This can be done by exploiting the fact that a function can be returned by a function.
wikipedia link

Partial Application: Passing less than the full argument list for the function.

map: List[A] => (A => B) : List[B]. Apply a function over a list and return the resulting list

flatMap: List[A] => (A => List[B]) : List[B] . Apply the function A => List[B]
on each element in List[A] and concatenate the results and return the concatenated results.

foldLeft: List => B => ((B, A) => b) : B . Iterate over the list from left to right starting with the value B, accumulate on B and return B. This is the same as the ruby inject method

FoldRight
List => B => ((A, B) => b) : B. same as foldLeft but iterates from right to left.

Associativity: Means that without changing the sequence of the operands, the order of calculation does not effect the result. i.e. (1 + 2) + 5 = 8 = 1 + (2 + 5)
wikipedia link
Commutativity: Changing the sequence of the operands does not effect the result i.e 1+ 2 + 5 = 8 = 5 + 2 + 1
wikipedia link


covariance: to be filled in

contravariance: to be filled in

functor: to be filled in

monad: to be filled in