[英]haskell recursive function
請幫助我編寫一個帶有兩個參數的函數:一個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 < 0 = x:xs
| n == 0 = (-x):xs
| otherwise = x:(myReverse xs (n-1))
那是從0
索引數組; 您的示例從1
索引,但在n == 0
的情況下未定義。 將其從1
索引的方法應該很明顯:)
另外,您的大小寫不一致; MyReverse
與myReverse
不同,只有myReverse
作為函數有效。
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
的無意義定義的更通用版本執行相同的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
myReverse xs i =
let j = i - 1
in take j xs
++ - (xs !! j)
: drop i xs
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.