Skip to content

Commit 9d71e3e

Browse files
committed
Add section on context bounds for polymorphic functions
1 parent 2c5b750 commit 9d71e3e

File tree

1 file changed

+27
-1
lines changed

1 file changed

+27
-1
lines changed

content/typeclasses-syntax.md

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,27 @@ The using clause in class `SortedSet` provides an implementation for the deferre
194194
**Alternative:** It was suggested that we use a modifier for a deferred given instead of a `= deferred`. Something like `deferred given C[T]`. But a modifier does not suggest the concept that a deferred given will be implemented automatically in subclasses unless an explicit definition is written. In a sense, we can see `= deferred` as the invocation of a magic macro that is provided by the compiler. So from a user's point of view a given with `deferred` right hand side is not abstract.
195195
It is a concrete definition where the compiler will provide the correct implementation.
196196

197-
### 5. Cleanup of Given Syntax
197+
### 5. Context Bounds for Polymorphic Functions
198+
199+
Currently, context bounds can be used in methods, but not in function types or function literals. It would be nice propose to drop this irregularity and allow context bounds also in these places. Example:
200+
201+
```scala
202+
type Comparer = [X: Ord] => (x: X, y: X) => Boolean
203+
val less: Comparer = [X: Ord as ord] => (x: X, y: X) =>
204+
ord.compare(x, y) < 0
205+
```
206+
207+
The expansion of such context bounds is analogous to the expansion in method types, except that instead of adding a using clause in a method, we insert a context function type.
208+
209+
For instance, type and val above would expand to
210+
```scala
211+
type Comparer = [X] => (x: X, y: X) => Ord[X] ?=> Boolean
212+
val less: Comparer = [X] => (x: X, y: X) => (ord: Ord[X]) ?=>
213+
ord.compare(x, y) < 0
214+
```
215+
216+
217+
### 6. Cleanup of Given Syntax
198218

199219
A good language syntax is like a Bach fugue: A small set of motifs is combined in a multitude of harmonic ways. Dissonances and irregularities should be avoided.
200220

@@ -325,7 +345,13 @@ TypeParamBounds ::= TypeAndCtxBounds
325345
TypeAndCtxBounds ::= TypeBounds [‘:’ ContextBounds]
326346
ContextBounds ::= ContextBound | '{' ContextBound {',' ContextBound} '}'
327347
ContextBound ::= Type ['as' id]
348+
349+
FunType ::= FunTypeArgs (‘=>’ | ‘?=>’) Type
350+
| DefTypeParamClause '=>' Type
351+
FunExpr ::= FunParams (‘=>’ | ‘?=>’) Expr
352+
| DefTypeParamClause ‘=>’ Expr
328353
```
354+
The syntax for function types `FunType` and function expressions `FunExpr` also gets simpler. We can now use a regular `DefTypeParamClause` that is also used for `def` definitions and allow context bounds in type parameters.
329355

330356
## Compatibility
331357

0 commit comments

Comments
 (0)