从 SML 中的列表中提取元素
我试图从列表中提取给定的元素,但出现匹配异常?
目标是让我的函数表现得像:
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
任何想法吗? 也许我可以使用更多列表函数来实现此目的? 我已经开始研究柯里化函数,它应该将一个函数变成一个高阶函数,但我真的不知道它是如何工作的?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
出现匹配错误的原因是,第二个列表不为空,但第一个列表不为空(这种情况总是会发生,除非第一个列表一开始就为空,因为只有第二个列表变短)。
基本上你可以将第一行更改为
fun extract _ [] = []
,它就会起作用。是的,您还可以使用高阶函数来解决这个问题。您可以使用
curry
将List.nth
转换为'a list ->; 类型的函数。整数-> 'a
而不是'a list * int -> 'a
.然后,您可以将该函数部分应用于xr
,这会将其转换为int ->; 类型的函数。 'a
,当给定数字i
时,它将返回xr
的第i
列表。然后,您可以使用List.map
将函数应用于给定的索引列表中的每个数字。所以这个函数就变成了:但是你想出的方法工作得很好,所以你应该坚持下去。
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 turnList.nth
into a function of type'a list -> int -> 'a
instead of'a list * int -> 'a
. You can then partially apply that function toxr
, which turns it into a function of typeint -> 'a
, which will return thei
th list ofxr
when given a numberi
. You can then useList.map
to apply the function to each number in the list of indices you're given. So the function becomes:But what you came up with works fine, so you should just stick with that.