Recursion help in OCaml - recursion

I'm trying to make a recursive function with Ocaml, but I keep getting the same error code.
let rec get x =
if x > 7 then
get x-7;;
And I get the very useful error message of:
Error: This expression has type int but an expression was expected of
type unit
I'm a complete beginner at OCaml, and studying it for a module at university.
And this is one of my assignments, and I'm a bit stuck!
I originally wanted to do it by a while loop, (as I'm a predominantly imperative programmer), but I couldn't get that to work, so I thought I'd try recursive!
Thanks

There's two problems with this code. First, the spacing of x-7 indicates that you would like to pass x - 7 to get, but it will actually be parsed as (get x) - 7. That's easily fixed with parentheses:
let rec get x =
if x > 7 then get (x - 7)
The second problem is that you don't have a second arm for the if, so the function doesn't have much of a chance of returning anything. (One arm if is taken to be of type unit, only useful for effects.)
You probably want to return something if x is less than 7, maybe:
let rec get x =
if x > 7 then get (x - 7) else x
Writing this with a while loop is possible, but you should understand that variables in OCaml are not mutable locations, only names. You'll have to introduce and manipulate mutable places explicitly:
let get x =
let y = ref x in
while !y > 7 do
y := !y - 7;
done;
!y
Hope that helps.

Related

F# Discriminated union with optional recurcive component

I'm working with F# and I struggle building my business model.
Let's say I have a list of float and two types of transformations I can apply on it.
By example:
type Transformation =
| SMA of period:Period
| P2MA of period:Period
Then I have defined a function let compute Transformation list to compute any kind of transformation over a list.
With the above Transformation type, I can create a SMA(3) or a P2SMA(5) by example.
I would like to be able to nest the transformations in a way I can write SMA(3, P2SMA(5, SMA(10))) by example. But also I would like to still be able to write SMA(2) only.
I tried using options, but I think writing SMA(3, None) or SMA(3, Some(P2SMA(5))) is too verbose.
Is there any way to do that? Maybe my approach is wrong, as I'm new in F#, I may tackle the problem by the wrong way?
Thanks a lot for the help
Try my answer here.
It's not possible to overload discriminated union cases in exactly the way you want. But if you'll accept a very slightly different syntax, you could do this instead:
type Period = int
type SmaTransform =
| Sma of Period
| Sma' of Period * Transform
and P2smaTransform =
| P2sma of Period
| P2sma' of Period * Transform
and Transform =
| OfSma of SmaTransform
| OfP2Sma of P2smaTransform
let SMA(period) =
Sma(period) |> OfSma
let SMA'(period, transform) =
Sma'(period, transform) |> OfSma
let P2SMA(period) =
P2sma(period) |> OfP2Sma
let P2SMA'(period, transform) =
P2sma'(period, transform) |> OfP2Sma
let transforms =
[|
SMA(3)
P2SMA(5)
SMA'(3, P2SMA'(5, SMA(10)))
|]
for transform in transforms do
printfn "%A" transform
The only difference from your desired syntax is the apostrophe that denotes a nested transform.
I tried using options, but I think writing SMA(3, None) or SMA(3, Some(P2SMA(5))) is too verbose.
You can use a static member with an optional argument:
type Transformation =
| [<EditorBrowsable(EditorBrowsableState.Never)>]
SMAInternal of period:int * inner: Transformation option
...
static member SMA(period:int, ?t:Transformation) =
SMAInternal(period, t)
You can then write: Transformation.SMA(3) or Transformation.SMA(3, Transformation.P2SMA(5)). This takes more characters but has fewer constructs. You may or may not regard it as more concise.
I'm new in F#, I may tackle the problem by the wrong way?
If you are going to be defining hundreds of these things in a code file then using the above approach and shortening the name Transformation may be a good idea. Otherwise just use the Somes and Nones. Verbosity is a negligible consideration and if you start to worry about it, horrible things start happening.
I don't understand quite what you're trying to model, but here is something hopefully similar.
My Transformations are either multiple a number or add to it
type Trans =
| Mult of period: int
| Add of period: int
and I can now write an interpret function, that given a number and a transformation, I can interpret it
let interpret x trans =
match trans with
| Mult p -> p * x
| Add p -> p + x
so we can now do simple
let x = interpret 1 (Mult 2)
but you want to chain transformations?
so lets allow that..
let interprets xs x =
List.fold (fun state trans ->
interpret state trans) x xs
and we can go...
let foo = [ Mult 3; Add 2 ]
let bar = interprets foo 1
OK, so IF you really want to deal with these compositions of lists of transformations uniformly, which may be nice (a bit like function composition).
Then i would be tempted to go (note I'm trying to follow your coding style)
(there's quite a lot to take in here, so maybe stick with the above approach until you're happy you understand F# a bit better).
type Trans =
| Mult of period: int
| Add of period: int
| Compose of chain: List<Trans>
let rec interpret x trans =
let interprets xs x =
List.fold (fun state trans ->
interpret state trans) x xs
match trans with
| Mult p -> p * x
| Add p -> p + x
| Compose ps ->
interprets ps x
let two = interpret 1 (Mult 2)
let three = interpret 1 (Compose [ Mult 2; Add 1 ])
Now I think you have a data model that "works", and is pretty simple.
I wouldnt then try to change the data model to make your code convenient, I'd create utility functions to do that (smart constructors) to do that.
e.g.
let multThen x trans = Compose [ Mult x; trans ]
let addThen x trans = Compose [ Add x; trans ]
The advice though is to make the data model model the data in the simplest manner, and then use functions to make your code elegant, and map in and out of that model, often the two things look quite different.
Caveat: I havent tested some of this code

Sum of Odds in OCaml

I have some code written in OCaml
let rec sumodds n =
if (n mod 2)<>0 then
let sum = sumodds (n-1) in
n + sum
else sumodds(n-1);;
and I am trying to add up all odd numbers from 0 to n, but I am not sure how to make the program stop once n reaches zero. If I could get some help that would be awesome. If there are any other mistakes in the program, feel free to let me know what they are.
The way to get the function to stop is to test for the "stop condition". I.e., you need to add an if statement that tests whether you have reached such a low value for n that the result is obvious.
Very commonly a recursive function looks like this:
let rec myfun arg =
if is_trivial_value arg then
obvious_answer
else
let s = myfun (smallish_part_of arg) in
combine arg s
You just need to add a test for the trivial value of your argument n.
Update
As #Goswin_von_Brederlow points out, another very common pattern for recursive functions is this:
let rec myfun2 accum arg =
if is_trivial_vaue arg then
accum
else
myfun2 (combine arg accum) (smallish_part_of arg)
This is the tail recursive transformation of the above form. You can code in either form, but they are different. So you need to keep them straight in your mind. As an FP programmer you need to (and will pretty easily) learn to translate between the two forms.
just add "if n <= 0 then n" in the 2nd line

Memoisation in OCaml and a Reference List

I am learning OCaml. I know that OCaml provides us with both imperative style of programming and functional programming.
I came across this code as part of my course to compute the n'th Fibonacci number in OCaml
let memoise f =
let table = ref []
in
let rec find tab n =
match tab with
| [] ->
let v = (f n)
in
table := (n, v) :: !table;
v
| (n', v) :: t ->
if n' = n then v else (find t n)
in
fun n -> find !table n
let fibonacci2 = memoise fibonacci1
Where the function fibonacci1 is implemented in the standard way as follows:
let rec fibonacci1 n =
match n with
| 0 | 1 -> 1
| _ -> (fibonacci1 (n - 1)) + (fibonacci1 (n - 2))
Now my question is that how are we achieving memoisation in fibonacci2. table has been defined inside the function fibonacci2 and thus, my logic dictates that after the function finishes computation, the list table should get lost and after each call the table will get built again and again.
I ran some a simple test where I called the function fibonacci 35 twice in the OCaml REPL and the second function call returned the answer significantly faster than the first call to the function (contrary to my expectations).
I though that this might be possible if declaring a variable using ref gives it a global scope by default.
So I tried this
let f y = let x = ref 5 in y;;
print_int !x;;
But this gave me an error saying that the value of x is unbounded.
Why does this behave this way?
The function memoise returns a value, call it f. (f happens to be a function). Part of that value is the table. Every time you call memoise you're going to get a different value (with a different table).
In the example, the returned value f is given the name fibonacci2. So, the thing named fibonacci2 has a table inside it that can be used by the function f.
There is no global scope by default, that would be a huge mess. At any rate, this is a question of lifetime not of scope. Lifetimes in OCaml last as long as an object can be reached somehow. In the case of the table, it can be reached through the returned function, and hence it lasts as long as the function does.
In your second example you are testing the scope (not the lifetime) of x, and indeed the scope of x is restricted to the subexpresssion of its let. (I.e., it is meaningful only in the expression y, where it's not used.) In the original code, all the uses of table are within its let, hence there's no problem.
Although references are a little tricky, the underlying semantics of OCaml come from lambda calculus, and are extremely clean. That's why it's such a delight to code in OCaml (IMHO).

Keeping a counter at each recursive call in OCaml

I am trying to write a function that returns the index of the passed value v in a given list x; -1 if not found. My attempt at the solution:
let rec index (x, v) =
let i = 0 in
match x with
[] -> -1
| (curr::rest) -> if(curr == v) then
i
else
succ i; (* i++ *)
index(rest, v)
;;
This is obviously wrong to me (it will return -1 every time) because it redefines i at each pass. I have some obscure ways of doing it with separate functions in my head, none which I can write down at the moment. I know this is a common pattern in all programming, so my question is, what's the best way to do this in OCaml?
Mutation is not a common way to solve problems in OCaml. For this task, you should use recursion and accumulate results by changing the index i on certain conditions:
let index(x, v) =
let rec loop x i =
match x with
| [] -> -1
| h::t when h = v -> i
| _::t -> loop t (i+1)
in loop x 0
Another thing is that using -1 as an exceptional case is not a good idea. You may forget this assumption somewhere and treat it as other indices. In OCaml, it's better to treat this exception using option type so the compiler forces you to take care of None every time:
let index(x, v) =
let rec loop x i =
match x with
| [] -> None
| h::t when h = v -> Some i
| _::t -> loop t (i+1)
in loop x 0
This is pretty clearly a homework problem, so I'll just make two comments.
First, values like i are immutable in OCaml. Their values don't change. So succ i doesn't do what your comment says. It doesn't change the value of i. It just returns a value that's one bigger than i. It's equivalent to i + 1, not to i++.
Second the essence of recursion is to imagine how you would solve the problem if you already had a function that solves the problem! The only trick is that you're only allowed to pass this other function a smaller version of the problem. In your case, a smaller version of the problem is one where the list is shorter.
You can't mutate variables in OCaml (well, there is a way but you really shouldn't for simple things like this)
A basic trick you can do is create a helper function that receives extra arguments corresponding to the variables you want to "mutate". Note how I added an extra parameter for the i and also "mutate" the current list head in a similar way.
let rec index_helper (x, vs, i) =
match vs with
[] -> -1
| (curr::rest) ->
if(curr == x) then
i
else
index_helper (x, rest, i+1)
;;
let index (x, vs) = index_helper (x, vs, 0) ;;
This kind of tail-recursive transformation is a way to translate loops to functional programming but to be honest it is kind of low level (you have full power but the manual recursion looks like programming with gotos...).
For some particular patterns what you can instead try to do is take advantage of reusable higher order functions, such as map or folds.

dynamic programming pseudocode for Travelling Salesman

this is a dynamic programming pseudocode for TSP (Travelling Salesman Problem). i understood its optimal substructure but i can't figure out what the code in red brackets do.
i am not asking anyone to write the actual code, i just need explanation on what is happening so i can write my own.... thanks:)
here is a link for the pseudocode, i couln't uploaded over here.
http://www.imagechicken.com/viewpic.php?p=1266328410025325200&x=jpg
Here is some less mathematical pseudo-code. I don't know if this will explain what's happening, but it may help you read it. This isn't a functional algorithm (lots of := all over), so I'm going to use Python pseudo-code.
# I have no idea where 'i' comes from. It's not defined anywhere
for k in range(2,n):
C[set(i,k), k] = d(1,k)
shortest_path = VERY_LARGE_NUMBER
# I have to assume that n is the number of nodes in the graph G
# other things that are not defined:
# d_i,j -- I will assume it's the distance from i to j in G
for subset_size in range(3,n):
for index_subset in subsets_of_size(subset_size, range(1,n)):
for k in index_subset:
C[S,k] = argmin(lambda m: C[S-k,m] + d(G,m,k), S - k)
shortest_path = argmin(lambda k: C[set(range(1,n)),k] + d(G,1,k), range(2,n))
return shortest_path
# also needed....
def d(G, i, j):
return G[i][j]
def subsets_of_size(n, s): # returns a list of sets
# complicated code goes here
pass
def argmin(f, l):
best = l[0]
bestVal = f(best)
for x in l[1:]:
newVal = f(x)
if newVal < bestVal:
best = x
bestVal = newVal
return best
Some notes:
The source algorithm is not complete. At least, its formatting is weird in the inner loop, and it rebinds k in the second argmin. So the whole thing is probably wrong; I've not tried to run this code.
arguments to range should probably all be increased by 1 since Python counts from 0, not 1. (and in general counting from 1 is a bad idea).
I assume that G is a dictionary of type { from : { to : length } }. In other words, an adjacency list representation.
I inferred that C is a dictionary of type { (set(int),int) : int }. I could be wrong.
I use a set as keys to C. In real Python, you must convert to a frozen_set first. The conversion is just busywork so I left it out.
I can't remember the set operators in Python. I seem to remember it uses | and & instead of + and -.
I didn't write subsets_of_size. It's fairly complicated.

Resources