myReverse :: [Int] -> Int -> [Int]
myReverse [] n = []
myReverse (x:xs) n
| n < 0 = x:xs
| n == 0 = (-x):xs
| otherwise = x:(myReverse xs (n-1))
That's indexing the array from 0
; your example indexes from 1
, but is undefined for the case n == 0
. The fix to take it to index from 1
should be fairly obvious :)
Also, your capitalisation is inconsistent; MyReverse
is different to myReverse
, and only the latter is valid as a function.
Results, in 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]
More generic version that does the same thing, using a pointless definition for 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