【问题标题】:Nested if statements in F#F# 中的嵌套 if 语句
【发布时间】:2016-02-15 16:18:34
【问题描述】:

我有以下代码

let rec function1 element1 element2 = function
        | [] -> []
        | [a;b;c;d;e;f]::t -> if true then if true then [a]::(function1 element1 element2 t) else (function1 element1 element2 t)
        | h :: t -> (function1 element1 element2 t);

,但它不会让我检查语句 1 和语句 2 是否为真

我不断得到

          | [a;b;c;d;e;f]::t -> if true then if true then [a]::(function1 element1 element2 t) else (function1 element1 element2 t)
  ------------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

stdin(3,31): error FS0001: This expression was expected to have type
    'a list    
but here has type
    unit    

我尝试了很多不同的东西,但似乎我在尝试一些不应该工作的东西。请帮忙

【问题讨论】:

    标签: f# functional-programming


    【解决方案1】:

    你的陈述被读作:

    if true
      then
        if true
          then something
          else somethingElse
      // missing else
    

    如果整体表达式的类型应为unit,则If 语句可能会省略else 分支。因此,当您省略 else 时,您可以考虑由编译器添加 else ()

    另一方面,您正在定义 match 语句应该返回一个列表。

    【讨论】:

      【解决方案2】:

      由于您有 2 个 if 但只有 1 个 else 分支,因此编译器将返回类型推断为单元,因为只有 1 个 if 表达式返回非单元。

      你可以解决这个问题

      1: 移除嵌套 - 当你可以 && 条件时它不是必需的

      2:添加额外的 else 分支(在你的情况下将返回 (function1 element1 element2 t))

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多