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

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

问题描述

我知道在某些语言(Haskell?)中,努力的目标是实现无点式的风格,或者永远不要按名称明确引用函数参数。这对我来说是一个非常困难的概念,但它可以帮助我理解这种风格的优点(或者甚至是缺点)。任何人都可以解释一下吗?

解决方案

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

  let sum = List.sum 
let sqr = List.map有趣的x - > x * x)

使用方式如下:

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

我们可以表达一个平方和函数为:

  let sumsqr x = sum(sqr x)

并使用:

  > sumsqr [3; 4; 5] 
50

或者我们可以通过管道x通过:

  let sumsqr x = x |> sqr |> sum 

这样写就很明显x仅在中传递 通过一系列功能进行线程化。直接构图看起来好多了:

  let sumsqr = sqr>>总和

这更简洁,它是对我们所做事情的不同思考方式;组成功能而不是想象参数流经的过程。我们没有描述 sumsqr 是如何工作的。我们正在描述它是什么



PS:一种有趣的方式可以让你的头脑组织化,如Forth,Joy,Factor等等。这些可以被认为只是组成(Forth :sumsqr sqr sum; ),其中单词之间的空格是组合运营商



PPS:也许其他人可以评论性能差异。在我看来,组成可以通过使编译器更加明显地减少GC压力,从而不需要像在流水线中一样产生中间值;帮助使所谓的森林砍伐问题变得更加轻松。

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?

解决方案

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)

Used like:

> 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)

And use like:

> sumsqr [3;4;5]
50

Or we could define it by piping x through:

let sumsqr x = x |> sqr |> sum

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

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: 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: 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天全站免登陆