Glenn
Glenn

Reputation: 27

Map with condition in Haskell

I want to make a mapping to an array with a function but only is a condition is fullfilled. For my particular problem I have an array of objects and only want to do a function on a sub-array of this big array.

function :: a -> a

mapping :: [a] -> [a] -> [a]
mapping all sub = map (\x -> if (x `elem` sub) then function x else x) all 

how can I do something like this ?

edit: I know this code works but in my class this is considered bad design and we need to avoid using if statements and need to use guards and such instead.

Upvotes: 1

Views: 880

Answers (2)

lsmor
lsmor

Reputation: 5063

If you are force to use guards, is pretty straightforward. I think if .. then .. else is a good pattern here though. As @dfeuer says, include the predicate and the function in mapping's signature.

mapping :: (a -> Bool) -> (a -> a) -> [a] -> [a]
mapping _ _ []     = []
mapping p f (a:as)
  | p a       = f a: mapping p f as
  | otherwise = a:mapping p f as

Upvotes: 0

dfeuer
dfeuer

Reputation: 48631

The part that seems like bad design to me is that you fail to factor out the basic pattern. As assembly.jc has pointed out, you should really give that its own function.

mapOnly :: (a -> Bool) -> (a -> a) -> [a] -> [a]
mapOnly p f = map $ \x -> if p x then f x else x

Using if seems quite reasonable style in this context; anything else really comes off as clunky.

Upvotes: 5

Related Questions