Vincent Zhou
Vincent Zhou

Reputation: 141

how to apply function to every element in a list in Haskell?

I want to apply resolve_on to every element in list c1, like

for(Char c:c1){
resolve_on c c1 c2;}

So how can I do this using map function?

resolvents :: [Char] -> [Char] -> [[Char]]
resolvents c1 c2 =  map (//what should I do) c1

resolve_on :: Char -> [Char] -> [Char] -> [Char]
resolve_on c c1 c2

Upvotes: 1

Views: 3736

Answers (1)

Will Ness
Will Ness

Reputation: 71065

When in doubt, start with list comprehensions:

-- for (Char c) in c1:                     do { c <- c1
--   yield (resolve_on c c1 c2)               ; return (resolve_on c c1 c2) }

resolvents c1 c2 = [ resolve_on c c1 c2 | c <- c1 ]

    -- read it:    a list of
    --              (resolve_on c c1 c2)
    --                                  for        -- or: for every
    --                                    c
    --                                      in c1

This is indeed a map,

                 = map (\c -> resolve_on c c1 c2) c1

This uses a lambda (i.e., unnamed) function, receiving one argument named c.

The do code in the comments would also work. It is in do notation, and is equivalent to the list comprehension.

Upvotes: 5

Related Questions