How do I write a loop in F# such that the value of a in the previous step is now assigned to b and so on?

68 views Asked by At

So, I have a little tricky assignment to solve and I am entirely new to functional programming. There is a list of boolean variables (neither strings nor chars cuz the algorithm only takes boolean variables so they were converted)

vars = [p;q;r] and there are 2 algorithms say A and B and one boolean equation eq1 = p & q The loop should perform something like this:

Step1 :let x = A ((B vars[0]) eq1) (The algorithm B works on vars[0] and then algorithm A works together on this and eq1) Step2 : let x1 = A ((B vars[1]) x) (In the next step, eq1 should be replaced with the answer from the previous step and algo B should work on vars[1] Step3: let x2 = A ((B vars[2]) x1)

In other languages, this can be written as a loop with the logic

foreach (i in vars){
 x = (A (B vars[i]) eq1)
 eq1 = x } 

Not sure how such a loop can be written in f#

2

There are 2 answers

0
smoothdeveloper On

Since the algorithm doesn't look like it needs an exit condition for the loop, I believe you can simply translate it using mutable variables for x and eq1, updated in a plain for loop.

let mutable x = ... // default value for x, pre loop
let mutable eq1 = ... // default value for eq1, pre loop
for i in vars do
  x <- A (B vars[i]) eq1
  eq1 <- x

notes:

  • F# doesn't mandate you take a "purely functional" approach, neither forbids mutability.
  • I'm not clear what i in vars and vars[i] means in your own code sample, it would clarify if you could show a complete working sample and the language it is written in.
0
Martin521 On

Should your assignment demand a "purely functional" approach, then you might want to look into recursive solutions or into the fold function. Below the same algorithm in three versions.

let f1 eq1 vars =
    let mutable x = eq1
    for v in vars do
        x <- A (B v) x
    x

let rec f2 x vars =
    match vars with
    | [] -> x
    | h::t -> f2 (A (B h) x) t

let f3 eq1 vars =
    (eq1, vars) ||> List.fold (fun x v -> A (B v) x)

Both the recursive solution f2 and the fold in f3 are quite common in the functional world. But, as mentioned by @smoothdeveloper, in F# you are free to also use other paradigms.

(The above assumes that eq1 is a bool value. You mentioned "equation", not sure if you mean "function", but that does not make sense in the code context that you have shown.)

Related Questions in F#

Related Questions in F#-INTERACTIVE