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

samfrances
  • 3,405
  • 3
  • 25
  • 40

4 Answers4

2

yes, for example, F# uses the forward pipe (|>) operator which makes the code very readable. for example,

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

and so on...

Alex
  • 2,342
  • 1
  • 18
  • 30
1

Frege has this, it is known as TDNR (type directed name resolution). Specifically, if x has type T, and y occurs in the namespace of T, then x.y is the same as (T.y x) which is in plain english y from the name space T applied to x.

Practical applications of this are: convenient syntax for record field access and access to native (i.e. Java, as Frege is compiled to Java) methods.

Ingo
  • 36,037
  • 5
  • 53
  • 100
0

Scala sounds like a good fit - it's a hybrid functional / object-oriented language.

Kevin Li
  • 1,540
  • 2
  • 17
  • 23
0

You don't need objects for that, just define your own reverse apply infix operator, which most functional languages allow you to do. Currying then does the rest. For example, in OCaml:

let (>>) x f = f x

Demo:

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

(Or choose whatever operator name you prefer; others use |> for example.)

Andreas Rossberg
  • 34,518
  • 3
  • 61
  • 72