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

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

  •  15-10-2022
  •  | 
  •  

Frage

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.

War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top