1

I've been investigating functional programming, and it occurred to me that there could be a functional language which has (immutable) objects with methods, and which therefore supports method chaining (where chainable methods would return new instances rather than mutating the instance the method is called on and returning it).

This would have readability advantages as...

o.f().g().h()

... is arguably more readable than:

h(g(f(o)))

It would also allow you to associate particular functions with particular types of object, by making them methods of those types (which I understand to be one advantage of object-oriented langauges).

Are there any languages which behave like this? Are there any reasons to believe that this would be a bad idea?

(I know that you can program like this in e.g Javascript, but Javascript doesn't enforce immutability.)

4

4 回答 4

2

是的,例如,F# 使用正向管道 (|>) 运算符,这使得代码非常易读。例如,

(1..20)
  |> Seq.map(functionFoo)
  |> Seq.map(functionBoo)

等等...

于 2013-01-29T19:47:38.030 回答
1

Frege有这个,它被称为 TDNR(类型定向名称解析)。具体来说,如果 x 具有类型 T,并且 y 出现在 T 的命名空间中,则与应用到 x 的命名空间 T中的普通英语yx.y相同。(T.y x)

这方面的实际应用是:记录字段访问和访问本地(即 Java,因为 Frege 被编译为 Java)方法的便捷语法。

于 2013-01-29T19:42:15.553 回答
0

您不需要对象,只需定义您自己的反向应用中缀运算符,大多数功能语言都允许您这样做。剩下的就是柯里化了。例如,在OCaml中:

let (>>) x f = f x

演示:

let f x y z = z * (x - y)
let g x = x + 1
let h x y = y * x

5 >> f 6 2 >> g >> h 2  (* = h 2 (g (f 6 2 5)) *)

(或选择您喜欢的任何运算符名称;|>例如其他人使用的名称。)

于 2014-01-14T08:21:44.503 回答
0

Scala听起来很合适——它是一种混合功能/面向对象的语言。

于 2014-01-13T21:24:24.863 回答