I'm a asked to write a filter function in SMLNJ

filter:  ('a  ->  bool)  *  'a  list  ->  'a  list

that takes a function f and a list L as parameters and returns a new list containing the elements l of L such that f(l) is true.

For example:

filter(fn(x  =>  x  mod  3  =  0),  [1,2,3,4,5,6,7,8,9,10])
returns  [3,  6,  9]

Due to lack of documentation of ML I'm stuck for hours on this function,

I'm wondering how to pass the second argument to the first argument.

有帮助吗?

解决方案

fun filter (f, []) = []
  | filter (f, x::xs) = if f x
                        then x::(filter (f , xs))
                        else filter (f , xs);

I'm not really sure what you mean about passing the second argument to the first argument.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top