我使用此函数来过滤整数列表。我正在乞求SML,但不知道错误在哪里。
fun filter f = fn [] => []
| fn (x::xs) => if f(x)
then x::(filter f xs) else (filter f xs)
fun g(x) = if x>5 then true else false
val listTest = filter g [1, 2, 4, 6, 8, 10]
谢谢!
答案 0 :(得分:0)
您第二个fn
是多余的,请删除它:
fun filter f = fn [] => []
| (x::xs) => if f(x)
then x::(filter f xs) else (filter f xs)
然后它可以愉快地编译:
- use "a.sml";
[opening a.sml]
val filter = fn : ('a -> bool) -> 'a list -> 'a list
val g = fn : int -> bool
val listTest = [6,8,10] : int list
val it = () : unit
顺便说一句,fun g(x) = if x>5 then true else false
并不是很好的风格。 fun g x = x > 5
更好
答案 1 :(得分:0)
带有fn
的定义看起来像带有fun
的定义,但是没有名称和箭头而不是=
:
fn a0 => e0
| a1 => e1
| ...
这是正确的:
fun filter f = fn [] => []
| (x::xs) => if f(x)
then x::(filter f xs)
else (filter f xs)
但常见形式是
fun filter _ [] = []
| filter f (x::xs) = if f x
then x :: filter f xs
else filter f xs
fun g x = x > 5