Haskell递归函数
请帮助我编写一个函数,该函数接受两个参数:整数列表和索引(int),并返回表中指定索引位置上具有负值的整数列表。
该函数将具有此签名MyReverse :: [Int]->Int->[Int]
。
例如:myReverse [1,2,3,4,5] 3 = [1,2,-3,4,5]
。
如果索引大于列表的长度或小于0,则返回相同的列表。
Please help me writing a function which takes two arguments: a list of ints and an index (int) and returns a list of integers with negative values on specified index position in the table.
The function would have this signatureMyReverse :: [Int]->Int->[Int]
.
For example: myReverse [1,2,3,4,5] 3 = [1,2,-3,4,5]
.
If the index is bigger than the length of the list or smaller than 0, return the same list.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是从
0
开始索引数组;您的示例从1
建立索引,但对于n == 0
的情况未定义。将其从1
索引的修复应该相当明显:)此外,您的大小写不一致;
MyReverse
与myReverse
不同,只有后者作为函数才有效。结果,在 GHCi 中:
执行相同操作的更通用版本,使用
myReverse
的毫无意义的定义:That's indexing the array from
0
; your example indexes from1
, but is undefined for the casen == 0
. The fix to take it to index from1
should be fairly obvious :)Also, your capitalisation is inconsistent;
MyReverse
is different tomyReverse
, and only the latter is valid as a function.Results, in GHCi:
More generic version that does the same thing, using a pointless definition for
myReverse
:myReverse :: [Int] ->整数-> [国际]
myReverse [] _ = []
myReverse 列表 n
|长度列表< n = 列表
myReverse (x:xs) n
|n == 0 = -x : myReverse xs (n-1)
|否则 = x : myReverse xs (n-1)
myReverse :: [Int] -> Int -> [Int]
myReverse [] _ = []
myReverse list n
|length list < n = list
myReverse (x:xs) n
|n == 0 = -x : myReverse xs (n-1)
|otherwise = x : myReverse xs (n-1)