I suggest we ...

Types with predicates to create subtypes easily (from Ada 2012)

I suggest introducing type predicates as an aspect that can be applied to declarations of enumeration types, discriminated union types and user-defined numeric types with the aim of creating subtypes easily.

Suppose, we are concerned with animal species and that we have a
type Animals thus:

type Animals =
| Tiger
| Lion
| Cat
| Mouse
| Hamster

Now suppose we wish to declare subtypes for predators and prey.
So we would like to declare a type Predators embracing Tiger, Cat and Lion, and a type Prey embracing Mouse and Hamster.

I suggest two ways to do this:
1) We can do this with an anonymous function performing pattern matching (subtype predicate in Ada 2012) by writing:

type Prey = Animals with function
| Mouse
| Hamster -> true
| _ -> false

type Predators = Animals with function Tiger | Cat | Lion -> true
| _ -> false

and then we are assured that objects of type Predators can only be Tiger, Cat or Lion, and objects of type Prey can only be Mouse or Hamster.

Another example:

type Even = int with function
| n when n % 2 = 0 -> true
| _ -> false

The aspect should be checked (checks for admissible values should be generated in compiled code by the F# compiler and performed) whenever an object of the type is default initialized, on assignments, on type casts, on parameter passing, in the match expressions and so on.

2) If we want to use a named function performing pattern matching, then we have to write:

type Animals =
| Tiger
| Lion
| Cat
| Mouse
| Hamster

let isPredator(animal: Animals): bool =
match animal with
| Tiger | Cat | Lion -> true
| _ -> false

type Predator = Animals with isPredator;

And last but not least, types with predicates should be allowed in a for loop meaning to try every value. So F# programmers should be able to write:

for animal in Predators do ...

for digit in Even do ...

Please see my previous suggestions for more details:
a) Allow enumeration type names and discriminated union type names in a for loop (from Ada 2012): https://fslang.uservoice.com/forums/245727-f-language/suggestions/12563118-allow-enumeration-type-names-and-discriminated-uni;
b) Allow basic integer numeric type names in a for loop (from Ada 2012): https://fslang.uservoice.com/forums/245727-f-language/suggestions/12564057-allow-basic-integer-numeric-type-names-in-a-for-lo

The suggested syntax allows writing clear, concise and easy-to-understand code. It will not affect existing codebase.
I think it will help bolster F# competitive strengths and improve its position in the TIOBE language popularity index.

7 votes
Vote
Sign in
(thinking…)
Sign in with: facebook google
Signed in as (Sign out)
You have left! (?) (thinking…)
Alexei Odeychuk shared this idea  ·   ·  Flag idea as inappropriate…  ·  Admin →

2 comments

Sign in
(thinking…)
Sign in with: facebook google
Signed in as (Sign out)
Submitting...

F# Language

Feedback and Knowledge Base