user2431438
user2431438

Reputation: 307

returning boolean value in function

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.

Upvotes: 1

Views: 5677

Answers (3)

Mark Pattison
Mark Pattison

Reputation: 3039

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.

Upvotes: 1

Lars
Lars

Reputation: 466

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

Upvotes: 1

John Palmer
John Palmer

Reputation: 25526

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

Upvotes: 4

Related Questions