Haskell 1级问题,感谢您的答案

发布于 2025-02-12 10:37:56 字数 358 浏览 0 评论 0原文

我是Haskell的新手,因此需要一些帮助,我想对你们很容易。 我正在尝试制作一个与使用“!”相同的函数。对于索引,但索引应从列表的长度从1变为。 这是我到目前为止的函数“ numberSlist”和MAIN函数“ Ele”

numberList :: [a] -> [(a, Int)]

numberList x = zip x [1..10]

ele :: Int -> [a] -> a

最终结果应该看起来像:

ELE 1 [1,2,3] = 1

ELE 2 [3,4,5,6] = 4

I I使用模式匹配尝试了一些不同的事情,但似乎不起作用。 我从这里去哪里?

I am new to Haskell and therefore needs some help which i guess is easy for you guys.
I am trying to make a function that does the same as using "!!" for indexes, but the indexes should go from 1 to the length of the list.
This is what i have so far, help function "numberList" and main function "ele"

numberList :: [a] -> [(a, Int)]

numberList x = zip x [1..10]

ele :: Int -> [a] -> a

End result should look like:

ele 1 [1,2,3] = 1

ele 2 [3,4,5,6] = 4

I have tried some different things with pattern matching, but it doesn't seem to work.
Where do i go from here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

遗弃M 2025-02-19 10:37:56

考虑您的两个示例:

ele 1 [1,2,3] = 1

ele 2 [3,4,5,6] = 4

在第一种情况下,由于数字为1,因此您返回了列表的头部。 简单。

ele :: Int -> [a] -> a
ele 1 (x:_) = x

因此我们需要将2 1获得。非常简单,从中减去1

但是,您还需要将4转到列表的头部。 ELE 1 [4,5,6]将为您提供所需的结果。此递归可能看起来如下,但是为了不为您做作业,我会让您填写空白。

ele :: Int -> [a] -> a
ele 1 (x:_) = x
ele n (x:xs) = ele (n-1) ?? 

Consider your two examples:

ele 1 [1,2,3] = 1

ele 2 [3,4,5,6] = 4

In the first case, because the number was 1, you returned the head of the list. Simple.

ele :: Int -> [a] -> a
ele 1 (x:_) = x

So we need to get that 2 to 1. Pretty easy, subtract 1 from it.

But you also need to get 4 to the head of the list. ele 1 [4, 5, 6] would handily give you the result you're looking for. This recursion might look like the following, but in the interest of not doing your homework for you, I'll let you fill in the blanks.

ele :: Int -> [a] -> a
ele 1 (x:_) = x
ele n (x:xs) = ele (n-1) ?? 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文