SML/NJ Write a filter function which takes a anonymous function as an argument

StackOverflow https://stackoverflow.com/questions/21977464

  •  15-10-2022
  •  | 
  •  

質問

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