F#中的嵌套if语句

时间:2016-02-15 08:10:03

标签: f# functional-programming

我有以下代码

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    

我尝试了很多不同的东西,看起来我似乎正在尝试一些不起作用的东西。请帮忙

2 个答案:

答案 0 :(得分:3)

您的陈述读作:

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

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

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

答案 1 :(得分:0)

由于你有2个但是只有1个其他分支,编译器已经将返回类型推断为单位,因为只有1个if表达式返回非单位。

您可以通过

解决此问题

1:取消嵌套 - 当你能够&& amp;&条件

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

相关问题