130624 (8) [Avatar] Offline
#1
8.4.2 Type inconsistencies
I was stumped on writing this function,

    let calculateRemainingPetrol(currentPetrol:int, distance:int) : int =

so I looked at the “solution”, which is clearly in error:

/// Calculates remaining petrol after driving
let calculateRemainingPetrol(currentPetrol, distance) =
    let remainingPetrol = currentPetrol - distance  //  what?
    if remainingPetrol >= 0 then remainingPetrol
    else failwith "Ooops! You ran out of petrol!"


The “units” of currentPetrol and distance are both ints, BUT currentPetrol is a measure of volume, whereas distance is a measure of length. Thus
    currentPetrol – distance
is nonsense.
Isaac Abraham (75) [Avatar] Offline
#2
Hey!

Thanks for the feedback. It's actually a very simplistic example where you can imagine that the car does 1 mile per gallon (or liter per kilometer depending on where you live smilie) - so distance can be equated to the total amount of petrol in the car. I'll try to get something added to this effect to make this clearer.

In a more fully featured example you could use F#'s Units of Measure to actually bake those two units into the type system so your code wouldn't even compile smilie
130624 (8) [Avatar] Offline
#3
YES! Looking fwd to specifying types, a la Pascal (wow! history!)
Isaac Abraham (75) [Avatar] Offline
#4
Have a look here docs.microsoft.com/en-us/dotnet/fsharp/language-reference/units-of-measure - it's quite powerful in that you can specify units against integers or floats etc. - so 5<km> is not the same as 5<liter> and couldn't be assigned.

This is covered in the appendices of the book - it's a not-often used feature in F# but extremely useful in such circumstances.
Isaac Abraham (75) [Avatar] Offline
#5
I've actually re-reviewed this - I'll probably make a small change to the source code. Apologies.
130624 (8) [Avatar] Offline
#6
Accepted! Carry on - you're teaching me.