I’m having a little trouble rewriting a method to use a higher-order function. Here’s the attempt (it compiles but doesn’t run it works fine):
fun lookup2 key hash =
List.foldr (fn ((k, v), r) => if k = key then SOME v else r) NONE hash;
Background:
The idea is that there is a hash like so and I’m lookup up an int option by string key:
- val h = [("a", 5), ("b", 4)];
- lookup "a" h;
val it = SOME 5 : int option
I wrote one that works just fine:
fun lookup _ nil = NONE
| lookup key ((k, v)::xs) = if k = key then SOME v else lookup key xs;
However I wanted to rewrite it to help get familiar with sml. I have a sneaking suspicion I don’t quite understand foldr…
My mistake – I was accidentally overwriting it with a different lookup2. It works as expected.
What you are looking for is not
List.foldr, butList.find:Now you can do the following:
Where
List.findreturns the matching tuple(key, val)orNONE, andOption.mapreturns eithervalfrom the tuple or alsoNONE.