returning boolean value in function

心已入冬 提交于 2019-12-24 08:49:08

问题


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.


回答1:


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



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/19195346/returning-boolean-value-in-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!