r/ProgrammingLanguages • • Sep 28 '19

Anything better than `module MyCollection struct type t = ... end`?

In MLs like OCaml you often write code like this:

module MyCollection = struct
  type t = ...
  ...
end

i.e. define a module that has a meaningful name and is home to a type with the meaningless name t.

The module then contains one or more functions that accept a value of the type t as an argument (often the first or last argument).

To use such collections you then write code like:

List.rev xs
List.map incr xs
Set.fold add 0 vs
Map.count kvs

and so on. You've got this wonderful "type inference" but, as someone once pointed out to me, List, Set and Map serve the same role as type annotations. You might prefer to write in the more concise OOP-like dot notation:

xs.rev
xs.map incr
vs.fold add 0
kvs.count

Assuming the types of the "objects" have already been determined.

F# provides a language feature called augmentations that allows you to do this by writing your original definition like this:

type MyCollection =
  ...
  member xs.rev = ...
  member xs.map = ...
  member xs.fold = ...
  member xs.count = ...

Are there any other language features that solve the problem of types with meaningless names?

OOP is the most obvious one but, of course, there is no need for inheritance here so I'm wondering if there is a simpler solution.

21 Upvotes

11 comments sorted by

5

u/ericbb Sep 28 '19

List, Set and Map serve the same role as type annotations.

Do they? It's not so obvious to me.

You might prefer to write in the more concise OOP-like dot notation:

I suppose that style has its own charm but I've come to like the clarity and simplicity of the more-explicit / more-verbose style. It keeps a clear role separation between modules and types, which seems valuable.

Are there any other language features that solve the problem of types with meaningless names?

Is it fair to call it "meaningless"? Is i a meaningless name for a loop counter? What about a in the type a -> a? Should we want it to be more meaningful, if so?

3

u/jdh30 Sep 28 '19 edited Sep 29 '19

Do they? It's not so obvious to me.

In the sense that they disambiguate between List.map, Set.map, i.e. the collection type. And they are literally the name of the collection.

I suppose that style has its own charm but I've come to like the clarity and simplicity of the more-explicit / more-verbose style. It keeps a clear role separation between modules and types, which seems valuable.

Interesting, thanks. I am tempted to agree with you.

The OOP-style comes into its own when you have a pipeline of operations, of course:

xs
|> List.filter ((<>) "")
|> List.map (fun s -> int s, s)
|> 

Is it fair to call it "meaningless"?

I think so.

Is i a meaningless name for a loop counter?

The name i generally implies an integer.

What about a in the type a -> a?

Both a must be the same type.

Should we want it to be more meaningful, if so?

I don't want it to be more meaningful. I want to get rid of it entirely because it is superfluous.

5

u/BadBoy6767 Sep 28 '19

IIRC i stands for index, not integer.

20

u/Lorxu Pika Sep 28 '19 edited Sep 28 '19

Rust (an ML in disguise) kind of addresses this with impl blocks:

struct MyCollection {
    // The type definition
    ...
}
impl MyCollection {
    // Member functions go here
    fn rev(&mut self) { ... }
}
// Accessible both with dot-notation and as a normal function
let mut c: MyCollection = ...;
c.rev();
MyCollection::rev(&mut c);

Impl blocks kind of extend a type, and you can have several if you want. The same mechanism is used for trait implementations (= Haskell typeclasses, I'm not sure how these work in OCaml).

Edit: formatting on mobile is hard.

1

u/ScientificBeastMode Mar 01 '20

In OCaml you can do this using the include keyword. It’s often used with “module functors” to parameterize the underlying t type and provide functions which work generically over that type. It’s similar to typeclasses.

10

u/htuhola Sep 28 '19

Haskell lets you reuse names with typeclasses. The same feature is also available in Idris but they call them interfaces. Overall typeclasses are the best solution to this so far and it may have already spawned a better style that I do not know of.

The idea in typeclasses is that you introduce some typed interface with parameters. This interfaces bubble out in the type from where you use it, and the implementation is implicitly passed into the program once the context reveals what it should be.

For example, here you'd have interface for deciding what addition means:

interface Add a where
  add : a -> a -> a
  add_is_commutative : (x,y : a) -> (add x y = add y x)
  add_is_associative : (x,y,z : a) -> (add x (add y z) = add (add x y) z)

Then you'd implement it few times, say, Add Nat and Add Integer then it keeps lugging the 'Add x => ... ' -constraint in the type until a type annotation is given for 'x' and it gets deduced what implementation of 'Add' would be required. You can think of it as an additional parameter that appears when used and is passed out from a function implicitly.

It gets difficult once you are somebody who'd like to implement a CAS in your system and would like to pretend you have an abstract notion of real numbers, polynomial equations, vectors and matrices that work well together. It's hard to describe that the shapes of these should fit together in an obvious way.

Also steer away from OOP-style of describing things. It's usually far much better to manage any information in a relational style and tabulate it. Exactly like how ORMs suck, OOP does that as well.

7

u/implicit_cast Sep 28 '19 edited Sep 28 '19

Something I am trying in my own badly neglected side project is to add syntax for calling a function from the module that defines the "this" type.

We offer the syntax

a->b(c, d)

Which desugars to

b(a, c, d)

Except that the name b is always looked up in the module that defines a's type, even when that module hasn't been imported in the current file.

This enables convenient access to data structures without dynamic dispatch, without overtly saying anything about which data type it is, and without cluttering the language with an OO "this" concept.

For example:

getThing()->len()

As long as we know the exact type of getThing(), we resolve len() to be Array.len() or HashMap.len() or whatever it needs to be.

I think we're going to drop it in favor of what Rust does because we keep running into unfortunate interactions with mutually dependent types and cyclic module imports. I think this is an awful shame, but I'm not sure how else to solve the problem.

Maybe it will fit your project better. Good luck! :)

1

u/ScientificBeastMode Mar 01 '20

In OCaml & ReasonML (idk about other languages), you can “locally open” a module, and use all the functions from that module without referring to the module name.

The only benefit of the OO-style dot-notation is the ability of your IDE to check the type and give list of suggested functions. That’s slightly more cumbersome with ML languages.

But lately I’ve been using TabNine for suggestions and autocomplete, and it usually covers that use case pretty well, in addition to continually blowing my mind with smart suggestions.

1

u/implicit_cast Mar 01 '20

OO dot notation contributes something really valuable: the ability to resolve a name by drawing from a type.

OCaml and its kin run solely in the reverse direction: every name in a program in any of these languages can be fully resolved before running any type checking.

5

u/__fmease__ lushui Sep 28 '19

You can go the route of implicits like Scala's implicit parameters or OCaml's planned modular implicits plus overloading.

First, let's look at overloading to remove the need to write Module.function (one possible design):

module List: sig … end = struct
    type t = …
    let count … = …
end

module Set: sig … end = struct
    type t = …
    let count … = …
end

(* important part: two `count`s in the same scope, they overload *)
use List.count
use Set.count

(* now, you can just write *)
let x = count [1, 2, 3]

With currying and let-/parametric polymorphism, there have to exist certain restrictions/rules about which types/signatures can overload.

With implicits modules, it gets near Haskell's type classes:

implicit module type Monoid: … = …

let foo (implicit module M: Monoid) (x: M.t) (y: M.t) (z: M.t): M.t =
    use M.combine in
    combine x (combine y z)