SML中的过滤器功能

时间:2018-10-15 20:47:36

标签: sml

我使用此函数来过滤整数列表。我正在乞求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] 

谢谢!

2 个答案:

答案 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