[英]apply a transformation with function inline
Starting from a simple case of "fold" (I used (+) but can be anything else): 从“ fold”的简单情况开始(我使用(+),但可以是其他任何东西):
Prelude.foldl (+) 0 [10,20,30]
is it possible apply an inline transformation similar to (that doesn't work): 是否可以应用类似于(无效)的内联转换:
Prelude.foldl ((+) . (\x -> read x :: Int)) 0 ["10","20","30"]
In case not, is there an alternative to fold, to apply a generic function and inline transformation (apart from using specific functions like 'sum', 'max' etc)? 如果没有,是否可以折叠,以应用通用函数和内联转换(除了使用诸如“ sum”,“ max”等特定函数之外)?
The read
lambda applies to the first argument and the first argument to the function given to foldl
is the accumulator. read
lambda适用于第一个参数,而赋予foldl
的函数的第一个参数是累加器。 Those two arguments are the opposite for foldr
. 这两个参数与
foldr
相反。 So, expanded, it looks like this: 因此,展开后,它看起来像这样:
foldl (\acc element -> (read acc :: Int) + element) 0 ["10", "20", "30"]
Since acc
is an Int
, this doesn't work. 由于
acc
是一个Int
,因此不起作用。
So, with this information in hand, you can do this with foldr
since it has the opposite argument order: 因此,掌握了这些信息后,您可以使用
foldr
进行此操作,因为它具有相反的参数顺序:
foldr ((+) . (read :: String -> Int)) 0 ["10","20","30"]
If you want an inline foldl
version, you can use flip
to achieve this. 如果要使用内联
foldl
版本,则可以使用flip
实现此目的。
You could also use map
first (everything else being equal, this would be the solution I'd prefer): 您还可以先使用
map
(在其他条件相同的情况下,这是我更喜欢的解决方案):
foldl (+) 0 $ map (read :: String -> Int) ["10","20","30"]
Also, you probably want foldl'
instead of foldl
. 另外, 您可能希望使用
foldl'
而不是foldl
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.