Problem #3
March 6, 2008 – 3:24 amSo the problem can be trivial using List.nth so I can go ahead and use that as my solution. But where is the fun in that?
Let’s try and learn something. We are not trying to be efficient, we are trying to learn something.
This will be a good place to start using recursion. The thing with functional programming is that you have to use a keyword to tell the compiler that this function is going to be called within the function itself.
So lets start off with the basic skeleton of a recursive function that iterates through a list.
#light
let rec p03 list =
match list with
| y::ys -> p03 ys
| [] -> []
The “rec” tells the compiler, that this function is recursive. The match list with is used to type match the list. The list is either empty or has some elements.
#light
let rec p03 list k =
match list with
| y::ys -> (match k with
| 1 -> y
| _ -> if (k > 1) then p03 ys (k - 1)
else y)
| [] -> []
This statement just adds another match statement within the first case. Also note the |_ ->, this tells the compiler for any other values go to this case. Then just a simple if else statement to catch negative numbers and this problem is solved.
Also as a general note, don’t use tabs with #light, it took me a while to figure this out.