haskell - 在 Haskell 中使用 2 个以上的参数进行柯里化(Currying)

标签 haskell currying pointfree tacit-programming

我开始学习 Haskell,所以我也需要了解柯里化(Currying)(这也是我第一次看到这种技术)。我想我知道它在某些情况下是如何工作的,其中 currification 只“消除”了其中一个参数。就像在下一个示例中,我试图计算 4 个数字的乘积。 这是 uncurried 函数:

prod :: Integer->Integer->Integer->Integer->Integer
prod x y z t = x * y * z * t

这是柯里化(Currying)函数:

prod' :: Integer->Integer->Integer->Integer->Integer
prod' x y z = (*) (x*y*z)

但我不明白如何继续这种动态,例如只使用两个参数执行相同的函数等等:

prod'' :: Integer->Integer->Integer->Integer->Integer
prod'' x y =

最佳答案

This is the uncurried function:

prod :: Integer -> Integer -> Integer -> Integer -> Integer
prod x y z t = x * y * z * t

已经是一个柯里化(Currying)函数。事实上,Haskell 中的所有函数都是自动柯里化(Currying)的。确实,您在这里编写了一个如下所示的函数:

prod :: Integer -> (Integer -> (Integer -> (Integer -> Integer)))

Haskell 将因此生成如下所示的函数:

prod :: Integer -> (Integer -> (Integer -> (Integer -> Integer)))
prod = \x -> (\y -> (\z -> (\t -> x * y * z * t)))

确实,例如我们可以生成这样的函数:

prod2 = prod 2

这将具有类型:

prod2 :: Integer -> (Integer -> (Integer -> Integer))
prod2 = prod 2

我们可以继续:

prod2_4 :: Integer -> (Integer -> Integer)
prod2_4 = prod2 4

最终:

prod2_4_6 :: Integer -> Integer
prod2_4_6 = prod2_4 6

编辑

prod' 函数有:

prod'' x y = (*) ((*) (x*y))

因为这意味着您将 (*) (x*y) 与下一个参数相乘。但是 (*) (x*y) 是一个函数。您只能将数字相乘。严格来说,您可以制作函数编号。但是 Haskell 编译器因此提示:

Prelude> prod'' x y = (*) ((*) (x*y))

<interactive>:1:1: error:
    • Non type-variable argument in the constraint: Num (a -> a)
      (Use FlexibleContexts to permit this)
    • When checking the inferred type
        prod'' :: forall a.
                  (Num (a -> a), Num a) =>
                  a -> a -> (a -> a) -> a -> a

因此,您在这里的目标是使用函数 a -> a 作为第一个操作数执行操作,但该函数不是 Num 的实例类型类。

关于haskell - 在 Haskell 中使用 2 个以上的参数进行柯里化(Currying),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58154012/

相关文章:

haskell - 在 Haskell 中提升类实例

scala - 理解 scala : currying

scala - 如何在 Scala 中对函数进行柯里化(Currying)

scala - 如何使用 orElse 组合返回 Option 的函数?

haskell - 使用带有 zipWithN 的运算符

haskell - 如何克服[cabal : error while loading shared libraries:] error on arch linux?

monads - 我应该避免使用 Monad 失败吗?

scala - Curried Scala 函数中的参数顺序

haskell - f x y = 3 + y/x(点自由形式)

haskell - 如何静态检查图形有效性?