从 SML 中的列表中提取元素

发布于 2024-09-30 02:46:59 字数 416 浏览 0 评论 0原文

我试图从列表中提取给定的元素,但出现匹配异常?

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

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

脸赞 2024-10-07 02:46:59

出现匹配错误的原因是,第二个列表不为空,但第一个列表不为空(这种情况总是会发生,除非第一个列表一开始就为空,因为只有第二个列表变短)。

基本上你可以将第一行更改为 fun extract _ [] = [] ,它就会起作用。

是的,您还可以使用高阶函数来解决这个问题。您可以使用 curryList.nth 转换为 'a list ->; 类型的函数。整数-> 'a 而不是 'a list * int -> 'a.然后,您可以将该函数部分应用于 xr,这会将其转换为 int ->; 类型的函数。 'a,当给定数字i时,它将返回xr的第i列表。然后,您可以使用 List.map 将函数应用于给定的索引列表中的每个数字。所以这个函数就变成了:

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

但是你想出的方法工作得很好,所以你应该坚持下去。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文