views:

151

answers:

1

I have homework where I am to update a list using a function that takes two elements and returns a value of part of the first element given in the function. So it's required to update the entire listing by going through each element and update its value by applying the function against all other elements in the list (including itself).

So far I've been trying to firstly map the list (so that each element is done the same) and then specifically update each elements value by mapping again just the value of the specified element however in trying to map just the specific value through: the function, the specific element and the entire list I keep getting complaints that I'm inferring the list of values made from the 'map function p@list list' rather than simply giving the value at p@list. Here is a sample of what I've been trying to implement:

res :: X -> X -> Z -- function given

myf :: [X] -> [X] -- Here is my function
myf ps = map newf ps
  where
    newf p@(X oldz) = X newz 
    newz = map (res p) ps 

Is this the correct method to try to update a list against the entire list itself?

EDIT: spelling mistakes and grammar- my apologies on not also putting the homework tag on it

+2  A: 

Is this the correct method to try to update a list against the entire list itself?

I'm not sure that code is correct for any task. Looks like you assumes that p@(X oldz) is taking element from list with constructor X oldz and names it p. But...

You need to describe how to behave when your list get changed after map (res p) is applied. If all your "changes" to list should be made only based on initial values of list and be applied in order from first element to last:

myf ps = (buildPlan ps) ps where
    buildPlan [] = id
    buildPlan (x:xs) = map (res x) . buildPlan xs

Some may prefer:

myf ps = changesPlan ps where
    change x = map (res x)
    changesPlan = foldr (.) id (map change ps)

If your "changes" to list should take changes from previous map (res x) (in non-func language while walking through list you change all elements even those which will be taken at next iteration):

myf ps0 = rebuildFrom 0 ps0 where
    rebuildFrom n ps | n >= length ps = ps
    rebuildFrom n ps = rebuildFrom (n+1) ps' where
        x = ps !! n
        ps' = map (res x) ps
ony