2013-10-09 68 views
1

我的测试函数有什么问题?F#函数类型不匹配

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) 

我得到一个编译器错误,第7行上的表达式具有函数类型,而不是bool。

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

回答

5

当您使用关键字function您正在创建一个implict lambda。据推测,对此的输入是int*int*int。为了解决这个问题刚刚得到改变

let rec test(a,b,c) = 

如果你想明确的论据,你也可以把它写成

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) 
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#时,这是一个常见问题。

我只发表这个作为答案,因为它有点太长的评论。