简体   繁体   English

将函数列表的组合应用于列表的每个编号

[英]Apply the composition of a list of functions to each number of a list

Given a list of functions and a list of numbers, I want first function to be applied to a list of numbers, the result then used for second function, and so on. 给定一个函数列表和一个数字列表,我希望将第一个函数应用于数字列表,然后将结果用于第二个函数,依此类推。

wantedFunc [(*2), (+2), (/2)] [1,2,3,4]
              |     |     |
              |     |     |
              V     |     |
        [2,4,6,8]---|     |
                    |     |
                    V     |
             [4,6,8,10]---|
                          V 
                      [2,3,4,5] -- End result

Is there a build-in function for this? 这是否有内置功能?

Something like 就像是

import Control.Arrow ((>>>))

wantedFunc :: Foldable t => t (a -> a) -> [a] -> [a]
wantedFunc fs = map f
  where
    f = compose fs
    compose = foldr (>>>) id

does the trick: 诀窍:

λ> wantedFunc [(*2), (+2), (/2)] [1, 2, 3, 4]
[2.0,3.0,4.0,5.0]

A right fold solution would be: 正确的折叠解决方案是:

fun :: (Functor f, Foldable t) => t (a -> a) -> f a -> f a
fun = foldr (\f -> (. fmap f)) id

then, 然后,

\> fun [(*2), (+2)] [1,2,3,4]
[4,6,8,10]

\> fun [(*2), (+2), (`div` 2)] [1,2,3,4]
[2,3,4,5]

Here's a fmap fmap approach, using a Monoid to compose the functions. 这是一个fmap fmap方法,使用Monoid来组合函数。

newtype Endo a = Endo { unwrap :: a -> a }

instance Monoid (Endo a) where
  mempty = Endo id
  mappend (Endo f) (Endo g) = Endo (g . f)

wantedFunc = unwrap . mconcat . fmap (Endo . fmap)

λ wantedFunc [(*2), (+2), (/2)] [1,2,3,4]
[2.0,3.0,4.0,5.0]

a one-liner solution can be 单线解决方案可以

> map (foldr (.) id $ reverse [(*2),(+2),(/2)]) [1..4]
[2.0,3.0,4.0,5.0]

Just compose all the functions and apply map. 只需撰写所有功能并应用地图。

wantedFunc :: [a->a] -> [a] -> [a]
wantedFunc fs = map (foldl1 (.) fs)

Applying directly your definition we get 直接应用您的定义我们得到

wantedFunc :: [(a -> a)] -> [a] -> [a]
wantedFunc fs xs = foldl (\ys f -> map f ys) xs fs

but we can transform 但我们可以改变

foldl (\ys f -> map f ys) xs fs
foldl (\ys f -> flip map ys f) xs fs    -- flip map
foldl (flip map) xs fs                  -- remove lambda
flip (foldl (flip map)) fs xs           -- flip foldl
flip (foldl (flip map))                 -- remove lambda
flip $ foldl $ flip map                 -- or using ($)

and finally 最后

wantedFunc :: [(a -> a)] -> [a] -> [a]
wantedFunc = flip $ foldl $ flip map

on the other hand we can change the function signature flipping arguments and the functions list order and we can write that function as 另一方面,我们可以更改函数签名翻转参数和函数列表顺序,我们可以将该函数编写为

wantedFunc' :: [a] -> [(a -> a)] -> [a]
wantedFunc' = foldr map

eg 例如

main = do
    print $ wantedFunc  [(*2), (+2), (/2)] [1,2,3,4]
    print $ wantedFunc' [1,2,3,4] [(/2), (+2), (*2)]

with output 与输出

[2.0,3.0,4.0,5.0]
[2.0,3.0,4.0,5.0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM