2017-09-10 20 views
-2

我想在ML中编写一个简单的过滤函数。这个想法是函数only_capitals接受一个字符串列表并返回一个字符串列表,只有以大写字母开头的字符串。下面是我的实现,但我得到一个类型错误,我不明白:ML List.filter中的类型不匹配

fun only_capitals (strs : string list) = 
    let 
    fun isCapitalized (str) = Char.isUpper(String.sub(str, 0)) 
    in 
    List.filter(isCapital, strs) 
    end 

以下是错误:

hw3provided.sml:5.18-5.27 Error: unbound variable or constructor: isCapital 
hw3provided.sml:5.6-5.34 Error: operator and operand don't agree [tycon mismatch] 
    operator domain: 'Z -> bool 
    operand:   _ * string list 
    in expression: 
    List.filter (<errorvar>,strs) 
val it =() : unit 
+0

那么,有什么错误? – melpomene

回答

2

第一个错误是由一个错字造成的; “isCapital”不是您定义的函数的名称。

第二个错误看起来很奇怪,因为第一个错误 - 类型_指的是isCapital的类型。
如果解决的第一个错误,第二个应该看起来更像

Error: operator and operand don't agree [tycon mismatch] 
    operator domain: 'Z -> bool 
    operand:   (string -> bool) * string list 
    in expression: 
    List.filter (isCapitalized,strs) 

什么编译器想说的是,你传递对(isCapitalized,strs)filter它预计'Z -> bool类型的函数。

如果你look at the type of List.filter,你会发现它是('a -> bool) -> 'a list -> 'a list - 这是一个咖喱饭功能。

你应该写什么是

fun only_capitals (strs : string list) = 
    let 
    fun isCapitalized (str) = Char.isUpper(String.sub(str, 0)) 
    in 
    List.filter isCapitalized strs 
    end 
+0

谢谢。完全忘记了咖喱。 –