Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# applying function to it's result n-times

I am trying to find a functional correct way for the following piece of code:

let mutable u = initialize cities pms
for i in 0 .. 10 do
    u <- randomIteration u pms distances

randomIteration is a simple function which takes an array with 2 more parameters and returns a modified array. This process has to be repeated n-times (10 here).

I came up with a solution, which uses fold, but I am creating a "dummy" sequence just to be able to fold on it, which does not seem right.

let result = Seq.init 10 (fun i -> i) |> Seq.fold (fun uNext i -> randomIteration uNext pms distances) u

I could also use recursion with a counter variable, but that as well seems ackward. Am I just missing a simple right solution?

like image 802
hoonzis Avatar asked Dec 05 '22 22:12

hoonzis


2 Answers

Just trying to think outside the box here, but instead of folding over randomIteration with different arguments each time, you could create a chain of N randomIteration calls and call this chain once:

let repeat n =
    Seq.init n (fun _ u -> randomIteration u pms distances)
    |> Seq.reduce (>>)

initialize cities pms
|> repeat 10
|> printfn "Result: %A"
like image 126
Nikon the Third Avatar answered Dec 15 '22 09:12

Nikon the Third


I could also use recursion with a counter variable, but that as well seems ackward.

That would seem natural to me: allowing the result of one call to be passed to the next without mutable state. Something like:

let interateSelf func initial count =
  let rec inner intermediate n =
    if n = 1 then
      func intermediate
    else
      inner (func intermediate) (n - 1)
  inner initial count
like image 41
Richard Avatar answered Dec 15 '22 09:12

Richard