F# - Ask for 3 numbers and then find the minimum?

Viewed 107

I am new to programming so this should be an easy one.

I want to write a code that asks for 3 numbers and then finds the minimum. Something like that:

let main(): Unit =
    putline ("Please enter 3 numbers:")
    putline ("First number: ")
    let a = getline ()
    putline ("Second number: ")
    let b = getline ()
    putline("Third number: ")
    let c = getline ()

    if (a<b && a<c) then putline ("Minimum:" + a)
    elif (b<c && b<a) then putline ("Minimum:" + b)
    else putline ("Minimum:" + c) 

I am sorry if this is terrible but I am still new to this. Also I am not allowed to use the dictionary. Any advice?

3 Answers

You can use the F# function min, which gives you the minimum of two values.

min 1 2 // 1

To get the minimum of three values you can use it twice:

min (min a b) c

A cleaner way to write this with F# piping is:

a |> min b |> min c

Alternatively, put the items in a list and use List.min:

[ a; b; c ] |> List.min

Firstly your putline function. I'm assuming that this is supposed to take a value and print it to the console with a newline, so the built in F# command to do this is printfn and you would use it something like this:

let a = 1
printfn "Minimum: %d" a

The %d gets replaced with the value of a as, in this case, a is an integer. You would use %f for a float, %s for a string... the details will all be in the documentation.

So we could write your putline function like this:

let putline s = printfn "%s" s

This function has the following signature, val putline : s:string -> unit, it accepts a string and return nothing. This brings us onto your next problem, you try and say putline ("Minimum:" + a). This won't work as adding a number and a string isn't allowed, so what you could do is convert a to a string and you have several ways to do this:

putline (sprintf "Minimum: %d" a)
putline ("Minimum:" + a.ToString())

sprintf is related to printfn but gives you back a string rather than printing to the console, a.ToString() converts a to a string allowing it to be concatenated with the preceding string. However just using printfn instead of putline will work here!

You also have a logic problem, you don't consider the cases where a == b == c, what's the minimum of 1,1,3? Your code would say 3. Try using <= rather than <

For reading data from the console, there is already an answer on the site for this Read from Console in F# that you can look at.

If, for some reason, you decide to expand beyond three numbers, you could consider using Seq.reduce

let xs = [0;-5;3;4]

xs
|> Seq.reduce min
|> printfn "%d"
// prints -5 to stdout

You can use min as the reducer because it accepts 2 arguments, which is exactly what Seq.reduce expects

Related