开发者

Help In Solving This Code In Haskell

The following code dosn't compile:

reindex :: (a -> a) -> [a]
reindex [] = []
reindex f y = let x = (zip [0..] y)
                  z = [(f m) |el <- x, let m = fst el]
              [n !! y | n <- z, (n !! y) > -1]

I get one of the following errors:

开发者_开发百科 a)
parse error on input `['

b)
 parse error on input `]'

I have tried to insert some while spaces infront or back of the last line but it is not working. It's making me more upset because i don't really know what is happening.

Need help

UPDATE

reindex takes a function and a list as arguments. It takes the indexes of the list one by one and applies the function to it to generate a new indexes. It will use the new generated indexes to retrieve the values from the original list to form a new list. If a new index is outside the bounds of the original list, that number is ignored.

examples:

Main> reindex (\x -> x + 1) [3,4,5]
[4,5]
Main> reindex (\x -> x - 2) [3,4,5]
[3]


Your function is really strange.

  1. The most obvious: You're missing the in at the end of let. Use where instead.
  2. Your type-signature is strange. Check it!
  3. Use pattern-matching instead of let in the definition of z.
  4. y can't be both a number and a list.

It may look like this:

reindex _ [] = []
reindex f y  = [n !! y | n <- z, (n !! y) > -1] where
  x = (zip [0..] y)
  z = [(f m) |(m,_) <- x]

But anyway, I don't really understand the code. If you explain, what it should do, we might find an easier solution for it.

Edit:

I would do what you want like this: (If other modules are allowed).

import Data.List
import Data.Function

reindex f list = map snd $ sortBy (compare `on` fst) newList where
    l = length list
    newIndizes = map f [0..]
    inList (x,_) = x >= 0 && x < l
    newList = filter inList $ zip newIndizes list

I think it's both easier to understand and faster (but please profile).

The behaviour is undefined, if the function may list a value twice. You can add this to fix it:

reindex f list = map snd $ sortBy (compare `on` fst) cleanedList where
  cleanedList =  nubBy ((==) `on` fst) newList

And this is your type-signature:

reindex :: (Int -> Int) -> [a] -> [a]


Your second line looks strange. Your function should expect a function from a to a and return a list of a, but then the pattern in your second line is just a list. That doesn't make sense to me.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜