简体   繁体   English

如何在 Scala 中组合柯里化函数

[英]How to compose curried functions in Scala

Is it possible compose functions in Scala that are curried?是否可以在 Scala 中组合柯里化函数? For example:例如:

def a(s1: String)(s2: String): Int = s1.length + s2.length
def b(n: Int): Boolean = n % 2 == 0

def x : String => String => Boolean = a andThen b

x("blabla")("foo") 

Edit :编辑 :

I've found a way of doing it in Haskell :我在 Haskell 中找到了一种方法:

a :: String -> String -> Int
a s1 s2 = length s1 + length s2

b :: Int -> Bool
b n = mod n 2 == 0

c :: String -> String -> Bool 
c = curry (b . (uncurry a))

This should work:这应该有效:

def x = a _ andThen (_ andThen b)

The first _ avoids invoking a and makes it into a function value.第一个_避免调用a并将其变成函数值。 This value is of type String=>String=>Int , ie a function that takes String and returns String=>Int .该值的类型为String=>String=>Int ,即一个接受String并返回String=>Int的函数。

The argument to the andThen method is a function that takes the result of the original function and modifies it. andThen方法的参数是一个函数,它接受原始函数的结果并对其进行修改。 So in this case it requires a function that takes String=>Int and returns a new value, a function String=>Boolean .所以在这种情况下,它需要一个接受String=>Int并返回一个新值的函数,一个函数String=>Boolean We can fabricate this new function by using andThen on the original function.我们可以通过在原始函数上使用andThenandThen这个新函数。 This takes the result of a and composes it with the new function b .这需要的结果, a和新功能组成它b

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

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