如何理解“Currying”在Haskell中? [英] How to understand the "Currying" in Haskell?

查看:139
本文介绍了如何理解“Currying”在Haskell中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个叫smallc的函数

  smallerc :: Integer  - > (整数 - >整数)
smallc xy =如果x <= y那么x else y

为什么不使用下面的方法来声明函数:

$ p $ lt; code> smallerc ::(Integer - > Integer) - > Integer

谢谢!

解决方案

理解currying的关键是理解不存在具有多于一个参数的函数。 haskell中的每个函数都只有一个参数。但是由于 - > 操作符的右联合属性,这并不是很清楚。



当你看到这个时:

 整数 - >整数 - >整数

相当于这个:

 整数 - > (整数 - >整数)

在这两种情况下,函数都需要一个整数返回一个函数。 (返回的函数是一个需要 Integer 并返回 Integer 的函数。)所以这可能类似于简单数学运算;它需要一个整数(假设为5)并返回一个函数,它接受另一个整数(5再次)并添加它到第一个,并返回结果(10)。

但是当你这样做时:

 (Integer  - >整数) - >整数

您已经创建了非常不同的东西 - 需要的功能一个函数并返回一个整型。这也可能是一种实现数学函数的方式;但是不要把 Integer 作为第一个参数,它需要数学运算本身!举个例子,假设你传递给这个函数一个函数,该函数将5传递给它。然后该函数将 5 传递给 函数,并返回结果(10)。

Assume there is a function called "smallerc"

    smallerc :: Integer -> (Integer->Integer)
    smallerc x y = if x <=y then x else y

Why not declare the function by using:

    smallerc :: (Integer -> Integer) ->Integer

Thank you!

解决方案

The key to understanding currying is to understand that there is no such thing as a function with more than one argument. Every function in haskell has exactly one argument. But because of the right-associative properties of the -> operator, that's not immediately clear.

When you see this:

Integer -> Integer -> Integer

It is equivalent to this:

Integer -> (Integer -> Integer)

In both cases, the function takes an Integer and returns a function. (The function returned is one that takes an Integer and returns an Integer.) So this might be something like a simple mathematical operation; it takes an Integer (let's say 5) and returns a function that takes another Integer (5 again) and adds it to the first one, and returns the result (10).

But when you do this:

(Integer -> Integer) -> Integer

You've created something very different -- a function that takes a function and returns an Integer. This could also be a way of implementing a mathematical function; but instead of taking an Integer as the first argument, it takes the mathematical operation itself! So for example, say you pass to this function a function that adds 5 to whatever is passed to it. This function then passes 5 to that function, and returns the result (10).

这篇关于如何理解“Currying”在Haskell中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆