“免费积分"的优缺点是什么?函数式编程的风格? [英] What are advantages and disadvantages of "point free" style in functional programming?

查看:23
本文介绍了“免费积分"的优缺点是什么?函数式编程的风格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在某些语言(Haskell?)中,努力是实现无点风格,或者从不通过名称显式引用函数参数.这对我来说是一个很难掌握的概念,但它可能有助于我理解这种风格的优点(甚至可能是缺点)是什么.谁能解释一下?

I know that in some languages (Haskell?) the striving is to achieve point-free style, or to never explicitly refer to function arguments by name. This is a very difficult concept for me to master, but it might help me to understand what the advantages (or maybe even disadvantages) of that style are. Can anyone explain?

推荐答案

我相信目的是要简洁,并将流水线计算表达为函数的组合,而不是考虑通过线程参数.简单示例(在 F# 中) - 给出:

I believe the purpose is to be succinct and to express pipelined computations as a composition of functions rather than thinking of threading arguments through. Simple example (in F#) - given:

let sum = List.sum
let sqr = List.map (fun x -> x * x)

用于:

> sum [3;4;5]
12
> sqr [3;4;5]
[9;16;25]

我们可以将平方和"函数表示为:

We could express a "sum of squares" function as:

let sumsqr x = sum (sqr x)

并使用类似:

> sumsqr [3;4;5]
50

或者我们可以通过管道 x 来定义它:

Or we could define it by piping x through:

let sumsqr x = x |> sqr |> sum

以这种方式编写,很明显 x 被传入 以通过一系列函数线程化".直接合成看起来好多了:

Written this way, it's obvious that x is being passed in only to be "threaded" through a sequence of functions. Direct composition looks much nicer:

let sumsqr = sqr >> sum

这更简洁,是对我们正在做的事情的另一种思考方式;组合函数而不是想象参数流过的过程.我们不是在描述 sumsqr 是如何工作的.我们正在描述它是什么.

This is more concise and it's a different way of thinking of what we're doing; composing functions rather than imagining the process of arguments flowing through. We're not describing how sumsqr works. We're describing what it is.

PS:了解组合的一个有趣方法是尝试使用连接语言(例如 Forth、Joy、Factor 等)进行编程.这些可以被认为只是组合(Forth : sumsqr sqrsum ;) 其中单词之间的空格是组合运算符.

PS: An interesting way to get your head around composition is to try programming in a concatenative language such as Forth, Joy, Factor, etc. These can be thought of as being nothing but composition (Forth : sumsqr sqr sum ;) in which the space between words is the composition operator.

PPS:也许其他人可以评论性能差异.在我看来,组合可以通过使编译器更明显来减少 GC 压力,因为无需像流水线那样生成中间值;帮助解决所谓的森林砍伐"问题.

PPS: Perhaps others could comment on the performance differences. It seems to me that composition may reduce GC pressure by making it more obvious to the compiler that there is no need to produce intermediate values as in pipelining; helping make the so-called "deforestation" problem more tractable.

这篇关于“免费积分"的优缺点是什么?函数式编程的风格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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