1
votes

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.

2
This smells like homework. If so, tag it as such. - Marcelo Cantos
itemInverse (or inverseItem) would be a better name, as "reverse" implies an entirely different operation on lists. - outis
or negateItem. Inverse can mean 1/x. - kennytm

2 Answers

4
votes
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
-1
votes
myReverse xs i =
    let j = i - 1
    in  take j xs
     ++ - (xs !! j)
      : drop i xs