【问题标题】:returning boolean value in function在函数中返回布尔值
【发布时间】:2013-10-05 07:49:57
【问题描述】:

我有这个功能:

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

这会返回一个错误,指出函数期望返回的值具有 bool 类型,而不是 unit。我想要实现的是在x != y 时返回true,因此循环应该停在那里;否则最后返回 false。

【问题讨论】:

  • 错误信息到底是什么?我认为问题在于没有 else 的简单 if 表达式不能返回任何值(单位除外)。原因是函数需要一些返回值,如果没有其他部分,则不能保证。

标签: f#


【解决方案1】:

在 F# 中,if 语句可以返回。结果,如果你把true放在它自己上,你需要把一个匹配的false,让if的两边都像这样返回bool

        if not (x = y) then
            true 
        else false

【讨论】:

    【解决方案2】:

    首先,“if x then true else false”与“x”相同。

    所以这个(你忘记了约翰指出的 else 部分):

    if not (x = y) then
       true
    else false
    

    可以简化为:

    x <> y
    

    不过,您的功能有点奇怪。我想这可能是你的意思:

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

    var1 和 var2 的检查可以移出 List.exists。所以:

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

    【讨论】:

      【解决方案3】:

      如果您想在找到匹配项后立即停止搜索,请尝试以下操作:

      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 接受一个返回布尔值的函数并遍历列表,直到找到该函数返回true 的元素,在这种情况下,它本身将返回true。如果它到达列表末尾但没有找到任何此类元素,它将返回false

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-06
        • 2021-10-29
        • 2013-03-11
        • 1970-01-01
        • 2021-01-05
        • 1970-01-01
        • 2017-06-07
        • 2011-07-22
        相关资源
        最近更新 更多