0

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.

3
  • 6
    This smells like homework. If so, tag it as such. Commented May 1, 2010 at 13:10
  • itemInverse (or inverseItem) would be a better name, as "reverse" implies an entirely different operation on lists. Commented May 1, 2010 at 13:12
  • or negateItem. Inverse can mean 1/x. Commented May 1, 2010 at 13:21

3 Answers 3

4
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
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, my solution didnt work because of lack ob brackets in (-x):xs thanks for help
@snorlaks: If you have a partial solution, people will always appreciate you posting it with the question, and saying what you've tried, where you think the problem is, etc.
0

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)

Comments

0
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)
   

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.