Scott Nimrod
Scott Nimrod

Reputation: 11595

How to return a value from a function based on conditions

I am not sure why the following function does not compile:

let isWithinRange (searchElement:int, recordLength:int) =
    if searchElement = recordLength then true
    elif searchElement > recordLength then false

As a result, I have to modify this function just for it to compile:

let isWithinRange (searchElement:int, recordLength:int) =
    let mutable withinRange = false
    if searchElement = recordLength then withinRange <- true
    elif searchElement > recordLength then withinRange <- false
    withinRange

I don't want to introduce mutability into my code.

Question:

  1. Why doesn't my original function compile?
  2. What do I need to do to make this function compile without introducing mutability?
  3. What's a better way to write this function?

NOTE:

I am new to F#. So please forgive me for this ignorant question.

Upvotes: 0

Views: 61

Answers (1)

rmunn
rmunn

Reputation: 36688

You're just missing a final else (value). The structure of your if statement is if...elif, but you need it to be if...elif...else, otherwise there's at least one code path through your function that doesn't return a value. Add else false to the end of your original function and your code will compile.

Also, the function name doesn't really make sense. Why are you comparing a search element to a record length? And why is that comparison called isWithinRange? As it stands, your function (at least the second version, which compiles) currently follows the following logic:

  1. If searchElement is equal to recordLength, return true.
  2. In all other cases, return false.

That could be written more simply as:

let isWithinRange (searchElement:int, recordLength:int) =
    (searchElement = recordLength)

Upvotes: 6

Related Questions