1

What's wrong with my test function?

let divisorOf(d, n) = n % d = 0

let notDivisible(d, n) = not (divisorOf(d, n))

let rec test(a, b, c) = function
  | (a, b, _) when (a > b) -> true
  | (a, b, c) -> notDivisible(a, c) && test(a + 1, b, c)

I'm getting a compiler error that the expression on line 7 has function type, not bool.

(7,40): error FS0001: This expression was expected to have type
    bool    
but here has type
    'a * 'a * 'b -> bool    
4

2 回答 2

5

当您使用关键字时function,您正在创建一个隐式 lambda。推断 this 的输入是一个int*int*int. 要解决这个问题,只需更改

let rec test(a,b,c) =

let rec test =

如果您想明确说明参数,也可以将其写为

let rec test(d, e, f) = match (d,e,f) with //change letters to avoid variable hiding
  | (a, b, _) when (a > b) -> true
  | (a, b, c) -> notDivisible(a, c) && test(a + 1, b, c)
于 2013-10-09T11:12:09.283 回答
2

约翰的回答是完全正确的,但为了其他可能阅读此内容的人,这是您发布的代码的更惯用的形式:

let divisorOf d n = n % d = 0

let notDivisible d n = not <| divisorOf d n
//Could also be let notDivisible d n = not(divisorOf d n)

let rec test =
    function
    | (a, b, _) when (a > b) -> true
    | (a, b, c) -> (notDivisible a c) && test (a + 1, b, c)

我只想指出这一点,因为在 divisorOf 和 notDivisible 上,您都为参数声明了一个元组,当不习惯编写 curried 参数的人开始编写 F# 时,这是一个常见问题。

我只将其发布为答案,因为评论太长了。

于 2013-10-09T18:15:39.540 回答