Search code examples
typessmlsmlnjcurrying

Handling anonymous functions in SML datatypes


I have the following datatype and 3 examples of tests:

datatype 'a test = Test of ('a -> bool) * string;
val pos = Test (fn x => x > 0, "pos");
val even = Test (fn x => x mod 2 = 0, "even");
val small = Test (fn x => x < 100, "small");

I'm still learning the ropes on SML, but I can't figure out how to "call" one of the tests as a recursive currying function. I tried with the following function but of course it wouldn't work. Anyone have any tips?

fun pass x [] = []
    | pass x (h::t) = (h x)::(pass x t);

pass: 'a -> 'a test list -> string list; 
i.e. pass' ~101 [pos, even, small] = ["small"]

Solution

  • I assume that you would like to filter test names in which a given input passes.

    You can do so by decomposing 'a test via pattern matching, getting corresponding functions and testing them on the current input:

    fun pass x [] = []
      | pass x (Test(f, s)::t) = if f x then s::pass x t 
                                 else pass x t