gruber
gruber

Reputation: 29779

haskell recursive function

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.

Upvotes: 0

Views: 1954

Answers (3)

vivian phung
vivian phung

Reputation: 39

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)
   

Upvotes: 0

vivian phung
vivian phung

Reputation: 39

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)

Upvotes: 0

me_and
me_and

Reputation: 15664

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

Upvotes: 4

Related Questions