简体   繁体   English

部分应用功能n次

[英]Partially apply function n times

Assume 假设

f x y z = x*y*z

Then I expect to return the application of f three times with each member of the list 然后我希望与列表的每个成员一起返回f的三次应用程序

foldl ($) f [1,2,3]

Something like (((f 1) 2) 3) = 1*2*3 = 6 类似(((f 1) 2) 3) = 1*2*3 = 6

The function f would be the accumulator and each iteration of the fold would apply one argument and return a partially applied function as the next accumulator. 函数f将是累加器,并且折叠的每次迭代将应用一个参数并返回部分应用的函数作为下一个累加器。

Why doesn't this work? 为什么这不起作用? Is it because f changes type while iterating? 是因为f在迭代时改变了类型吗?

As an aside: is there any other way to accomplish this type of function application? 旁白:有没有其他方法可以完成这种类型的功能应用程序?

The types look like 类型看起来像

foldl :: (a -> b -> a) -> a -> [b] -> a

($) :: (x -> y) -> x -> y

To apply foldl to ($) requires matching (technically, unifying) the type of the first argument to foldl with the type of ($) . 要应用foldl($)需要匹配(技术上,统一)的第一个参数的类型foldl同类型($) That is, solving the equation 也就是说,求解方程式

a -> b -> a  =  (x -> y) -> x -> y

This leads immediately to 这导致立即

a = x -> y
b = x
a = y

Substituting the second and third equations into the first: 将第二个和第三个方程式代入第一个方程式:

a = b -> a

The problem is that Haskell has no type that solves this equation. 问题是Haskell 没有解决这个等式的类型 In particular, it is impossible to write down a solution with a finite number of symbols! 特别是,不可能用有限数量的符号写下解决方案! It expands first to 它首先扩展到

a = b -> b -> a

then 然后

a = b -> b -> b -> a

and on forever. 永远。 So there is no way to choose types for the type variables to make them match, and GHC will complain loudly. 所以没有办法为类型变量选择类型以使它们匹配,GHC会大声抱怨。

In general, you can't do what you're trying to do because the type system distinguishes between functions with different numbers of arguments. 一般来说,你不能做你想要做的事情,因为类型系统区分具有不同数量的参数的函数。 What you're trying to do, essentially, is convert a list of values into a list of arguments for a function, which doesn't make sense in context. 实际上,您要做的是将值列表转换为函数的参数列表,这在上下文中没有意义。

However, the instance you're pointing at is literally just foldl (*) . 但是,您指向的实例实际上只是foldl (*) If you're performing the same operation on all of the variables in a function, you can just use this (well, you should be using either foldl' or foldr , but you get the idea). 如果你对函数中的所有变量执行相同的操作,你可以使用它(好吧,你应该使用foldl'foldr ,但你明白了)。

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

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