List haskell递归函数
请帮助我编写一个函数,它接受两个参数:一个int列表和一个索引(int),并返回一个在表中指定索引位置上具有负值的整数列表 函数将具有此签名List haskell递归函数,list,haskell,recursion,List,Haskell,Recursion,请帮助我编写一个函数,它接受两个参数:一个int列表和一个索引(int),并返回一个在表中指定索引位置上具有负值的整数列表 函数将具有此签名MyReverse::[Int]->Int->[Int] 例如:myReverse[1,2,3,4,5]3=[1,2,-3,4,5] 如果索引大于列表长度或小于0,则返回相同的列表 myReverse :: [Int] -> Int -> [Int] myReverse [] n = [] myReverse (x:xs) n | n <
MyReverse::[Int]->Int->[Int]
例如:myReverse[1,2,3,4,5]3=[1,2,-3,4,5]
如果索引大于列表长度或小于0,则返回相同的列表
myReverse :: [Int] -> Int -> [Int]
myReverse [] n = []
myReverse (x:xs) n
| n < 0 = x:xs
| n == 0 = (-x):xs
| otherwise = x:(myReverse xs (n-1))
对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
myGeneric::(a->a)->[a]->Int->[a]
myGeneric f[]n=[]
myGeneric f(x:xs)n
|n<0=x:xs
|n==0=(fx):xs
|否则=x:(myGeneric f xs(n-1))
myReverse::[Int]->Int->[Int]
myReverse=myGeneric否定
这闻起来像是家庭作业。如果是这样,请将其标记为这样。itemsinverse
(或inverseItem
)将是一个更好的名称,因为“reverse”意味着对列表执行完全不同的操作。或inverseItem
。反向可以表示1/x。谢谢,我的解决方案不起作用,因为(-x):xs中缺少ob括号谢谢help@snorlaks:如果你有一个局部的解决方案,人们会很感激你把它和问题一起发布,并说你尝试过什么,你认为问题在哪里,等等。这是非常不惯用的Haskell,而且效率很低。哦,那是ttricku,但很有趣,你能一步一步地给我解释一下这个例子吗?感谢helplet j=i-1在需要更改的元素之前为您提供该元素的索引。假设jxs在i“++”是列表连接“!!”是索引“:”将求反的值放在drop i的头上xs drop i xs是删除了第一个i元素的列表xs。所以它把列表分为我之前的部分,否定的部分和我之后的所有部分,然后把它们粘在一起
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
myReverse xs i =
let j = i - 1
in take j xs
++ - (xs !! j)
: drop i xs