在函数中返回布尔值

在函数中返回布尔值

问题描述:

我有这个功能:

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

这将返回一个错误,表明函数期望返回的值具有布尔类型,而不是单位类型.我想要实现的是每当 x!= y 都返回true,因此循环应在此处停止;否则最后返回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.

在F#中,如果语句可以返回.结果,如果您单独放置 true ,则需要放置一个匹配的false,以便 if 的两面都这样返回bool

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