开发者

Extracting elements from list in SML

开发者 https://www.devze.com 2023-01-22 21:15 出处:网络
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:

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 t开发者_StackOverflowhis? 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消