【问题标题】:haskell recursive functionhaskell 递归函数
【发布时间】:2011-02-14 13:14:40
【问题描述】:

请帮助我编写一个函数,它接受两个参数:一个整数列表和一个索引 (int),并返回一个整数列表,该列表在表中的指定索引位置具有负值。

该函数将具有此签名MyReverse :: [Int]->Int->[Int]

例如:myReverse [1,2,3,4,5] 3 = [1,2,-3,4,5]

如果索引大于列表长度或小于0,则返回相同的列表。

【问题讨论】:

  • 这闻起来像家庭作业。如果是这样,请将其标记为这样。
  • itemInverse(或inverseItem)会是一个更好的名称,因为“反向”意味着对列表进行完全不同的操作。
  • negateItem。逆可以表示 1/x。

标签: list haskell recursion


【解决方案1】:
myReverse :: [Int] -> Int -> [Int]
myReverse [] n = []
myReverse (x:xs) n
 | n < 0     = x:xs
 | n == 0    = (-x):xs
 | otherwise = x:(myReverse xs (n-1))

这是从0 索引数组;您的示例索引来自1,但对于n == 0 的情况未定义。将其从1 索引的修复应该相当明显:)

另外,您的大小写不一致; MyReversemyReverse 不同,只有后者作为函数有效。

GHCi 中的结果:

*Main> myReverse [10,20,30,40,50] 0
[-10,20,30,40,50]
*Main> myReverse [10,20,30,40,50] 2
[10,20,-30,40,50]
*Main> myReverse [10,20,30,40,50] 3
[10,20,30,-40,50]
*Main> myReverse [10,20,30,40,50] 5
[10,20,30,40,50]
*Main> myReverse [10,20,30,40,50] (-1)
[10,20,30,40,50]

做同样事情的更通用的版本,对myReverse使用毫无意义的定义:

myGeneric :: (a -> a) -> [a] -> Int -> [a]
myGeneric f [] n = []
myGeneric f (x:xs) n
 | n < 0     = x:xs
 | n == 0    = (f x):xs
 | otherwise = x:(myGeneric f xs (n-1))

myReverse :: [Int] -> Int -> [Int]
myReverse = myGeneric negate

【讨论】:

  • 谢谢,由于 (-x) 中缺少 ob 括号,我的解决方案不起作用:xs 感谢您的帮助
  • @snorlaks:如果您有部分解决方案,人们将始终感谢您将其与问题一起发布,并说出您尝试过的方法,您认为问题出在哪里等。
猜你喜欢
  • 2019-02-28
  • 1970-01-01
  • 2017-01-20
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 2015-05-09
相关资源
最近更新 更多