Understanding if conditions in F#

Hi,

I am trying to solve some puzzles in F#. I am a bit confused by the way its if works. I got that if is a function with return parameter and return datatype and that it should be consistent between al cases. I am trying to translate this code to F#

int a = 0;
int b = 0;
int n = int.Parse(Console.ReadLine());
{...}
for (int i = 0; i < n; i++)
        {
            int c = int.Parse(inputs[i]);
            if (c > a)
            {
                a = c;
            }
            else if (c < b)
            {
                b = c - a;
            }
        }
{...}
Console.Writeline(a);

After a bit of struggling I finally got a code that does compile:

let a = 0
let b = 0
let n = int(Console.In.ReadLine())
{...}
for i in 0 .. n - 1 do
    let c = int(words.[i])
    let temp = c - a
    a = if c > a then c else a
    b = if c < b then temp else b
    ()
{...}
printfn "%d" a

As I said, the code compiles, however printfn always return the initialisation value of a. This, despite the fact that c is bigger than a at some iterations. The debug output used at the end of the for loop shows that a is always constant. What am I doing wrong?

Does your code really compile? I’m far from being an expert in F#, but there seems to be some let missing around. Anyway, the following snippet should work as you expect:

let mutable a = 0
let mutable b = 0
let n = int(Console.In.ReadLine())
{...}
for i in 0 .. n - 1 do
    let c = int(words.[i])
    let temp = c - a
    a <- if c > a then c else a
    b <- if c < b then temp else b
    ()
{...}
printfn "%d" a

It’s highly un-functional however. A more functional style will give something like that:

let n = int(Console.In.ReadLine())
let cs = Seq.append (Seq.map int (Seq.take n words)) [0]
let a = Seq.max cs
let b = Seq.min cs

printfn "%d" a

As you can see, the functional version usually puts a greater emphasis on what you want instead of how to get it.

4 Likes

Yeah… with Functional Programming you have to approach all problems and issues in a completely different mindset.

This is why I’ve yet to really start doing puzzles in Haskell, F#, etc.

Though… there are some puzzles that would be easier in those languages mindsets.

1 Like

Thanks a lot. Your approach seem to work. I still have to cross the “thinking gap” when it comes to this kind of language '^^

1 Like