2

我试图从列表中提取给定的元素,但我得到一个匹配异常?

目标是让我的函数表现得像:

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

我正在尝试这样做:

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

但正如所说,我得到一个

! Uncaught exception: 
! Match

有任何想法吗?也许我可以使用更多的 List 函数?我已经了解了 curry 函数,它应该将一个函数变成一个高阶函数,但我真的不知道它是如何工作的?

4

1 回答 1

1

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.

于 2010-11-02T13:04:15.567 回答