1
votes

I have this function:

let myFunction list (var1, var2) : bool =
    for (x,y) in list do
        match (var1, var2) with
        | (1, 11) | (2, 22) -> true
        | (_, _) ->
            if not (x = y) then
                true // error is here
            false

This returns an error saying that the function expects the value returned to have type bool, not unit. What I want to achieve is to return true whenever x != y so the loop should stop there; otherwise to return false at the end.

3
What exactly was the error message? I assume that the problem is that a simple if-expression without else cannot return any value (other than unit). The reason is that the function needs some return value and if there is no else-part, this is not guaranteed. - fsharpnoob

3 Answers

4
votes

In F#, if statements can return. As a result, if you put the true on its own, you need to put a matching false so that both sides of the if return bool like so

        if not (x = y) then
            true 
        else false
1
votes

First, "if x then true else false" is the same as "x".

So this (you forgot the else-part as John pointed out):

if not (x = y) then
   true
else false

can be simplified to:

x <> y

Your function is a bit weird though. I think this might be what you mean:

let myFunction list (var1, var2) =
    List.exists (fun (x, y) -> match (var1, var2) with
                               | (1, 11) | (2, 22) -> true
                               | _ -> (x <> y))
                list

The check of var1 and var2 can be moved out of List.exists. So:

let myFunction list = function
                      | (1, 11) | (2, 22) -> true
                      | _ -> List.exists (fun (x, y) -> x <> y) list
1
votes

If you want to stop searching as soon as a match is found, try something like:

let myFunction list (var1, var2) : bool =
    match (var1, var2) with
    | (1, 11) | (2, 22) -> true
    | _ -> Seq.exists (fun (x, y) -> x <> y) list

Seq.exists takes a function returning a boolean and goes through the list until it finds an element for which the function returns true, in which case it will itself return true. If it reaches the end of the list without finding any such elements, it will return false.