Question

I'm trying to extract the given elements from a list, but I get an Match exception?

The goal is to make my function behave like:

fun extract [#"a",#"b",#"c"] [0,1,0] = [#"a",#"b",#"a"];

And I'm trying to do it like this:

fun extract [] _ = []
  | extract xr (y::yr) = List.nth(xr, y) :: extract xr yr;

But as said, I get an

! Uncaught exception: 
! Match

Any ideas? Maybe theres some more List functions I could use for this? I've head about the curry function, which should make a function into a higher-order function, but I don't really know how that works?

Was it helpful?

Solution

The reason that you get a match error is that there's no case for when the second list is empty, but the first is not (which will always happen unless the first list is empty to begin with because only the second list gets shorter).

Basically you can change the first line to fun extract _ [] = [] and it will work.

And yes, you can also solve this using higher-order function. You can use curry to turn List.nth into a function of type 'a list -> int -> 'a instead of 'a list * int -> 'a. You can then partially apply that function to xr, which turns it into a function of type int -> 'a, which will return the ith list of xr when given a number i. You can then use List.map to apply the function to each number in the list of indices you're given. So the function becomes:

fun extract xr yr = List.map (curry List.nth xr) yr

But what you came up with works fine, so you should just stick with that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top