views:

136

answers:

2

Hello,

Please help me with writing function which takes two arguments : list of ints and index (int) and returns list of integers with negative of value on specified index position in the table

MyReverse :: [Int]->Int->[Int]

for example

myReverse [1,2,3,4,5] 3 = [1,2,-3,4,5]

if index is bigger then length of the list or smaller then 0 return the same list.

Thanks for help

+4  A: 
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
me_and
thanks, my solution didnt work because of lack ob brackets in (-x):xsthanks for help
gruber
@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.
me_and
A: 
myReverse xs i =
    let j = i - 1
    in  take j xs
     ++ - (xs !! j)
      : drop i xs
FredOverflow
This is very non-idiomatic Haskell, and very inefficient.
MtnViewMark
Ohhh thats ttricku, but interesting, could You please explain that example for me step by step ?thanks for help
gruber
let j = i -1 gives you the index to the element just before the one that needs to be changed.take j xs gives you a list of elements before i"++" is list concatenation"!!" is index":" puts the negated value on to the head of drop i xsdrop i xs is the list xs with the first i elements removed.So it splits the list into the before i part the negated i part and everything after i then it glues it all back together
stonemetal