Reputation: 141
First of all, I am a complete beginner to functional programming and F#. I am kinda getting into the basic concepts and I tried to start practicing my understanding by writing a Mandelbrot set program.
The function iterate
should take a tuple, iterate over it, and in case the exit condition infinity
is med, it should return the amount of iterations i
it took. Else it calls itself with the changed tuple.
I receive the following error: FS0001 Should be "int32", is "unit" instead
line 2
Edit: mandelbrot takes a tuple and return a tuple; infinity takes a tuple and return an integer
let rec iterate (a, b) :int32 =
for i:int32 in 0..100 do
(a, b)
|> mandelbrot
|> match infinity with
| a when a > 16 -> i
| a when a <= 16 -> iterate (a, b)
Upvotes: 0
Views: 84
Reputation: 141
Before I try to explain the function unnecessarily here is how the code would look like written in C:
int iterate(int a, int b) { int i, ca = a, cb = b, aa, bb;
for (i = 0; i <= 100; i++) {
aa = a * a - b * b; //mandelbrot algorithm
bb = 2 * a * b;
a = aa + ca;
b = bb + cb;
//checks if the the values deviate to infinity
if ((a + b) > 16) {
return i;
}
}
}
I thought about using recursion but since Iam not used to the functional paradigm I tried to avoid it for efficiency reason and basically tried to create a break condition. Turns out, F# compiles tail recursion into while loops so all this was just really unnecessary and dumb. https://gist.github.com/mrange/3a275cc643c9753925f1c8a68b0bd7a0
Still hope it helps someone and thanks for everyone that tried to make sense out of the code I wrote.
Upvotes: -1
Reputation: 2436
It's hard to guess what you want to achieve. However a few tweaks could get you to compile. A for do
expects a function returning unit
e.g. a statement.
If you want go through iterate up to a hundred times you could use a variable i that you pass inside the iteration and you increase it each time you make a call and initialize it with 0 e.g. iterate (2,3) 0
let mandelbrot (a,b) = (a,b)
let infinity (a,b) = a
let rec iterate (a, b) i :int =
(a, b)
|> mandelbrot
|> infinity
|> (fun a-> if i=100 then a else
match a with
| a when a > 16 -> i
| _ -> iterate (a,b) (i+1))
Upvotes: 2