is it possible for a function to return an integer or string depending on the input?

Short answer is no. Like you said F# only allows one return type.

In this case your result type has 2 possible set of values, the Ok values and the Error values. Your code needs to consider both posibilites, you cannot ignore one. Remember eval a does not return an int anymore, now it returns a result, which may or may not have an int inside it.

After you eval a and eval b but before you call +, -, * or /, you need to check if either result is an Error. Only if both are Ok can you then apply the operator. If any of them is an Error you have to return the error, right?

You can use match to check (and to extract the int), for instance:

match eval  a , eval  b  with
|     Ok    a', Ok    b' -> Ok(a' + b')
|     Error e , _    
|     _       , Error e  -> Error e

Remember you do not need to copy the instruction above 4 times. You can create a function and pass the operator as a parameter using this syntax: (+), (-), (*), (/).

Another tip: you are considering only the case of division by Const 0. What happens if you are dividing by a calculated 0, for instance 5/(1 - 1)?

In Functional Programming there is another way of dealing with this. What you need in the end is a Bind function (or Apply). A good resource to learn about it is this site: https://fsharpforfunandprofit.com/rop/

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top