-
Notifications
You must be signed in to change notification settings - Fork 59
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1079 from hylo-lang/optional
Add 'Optional' to the standard library
- Loading branch information
Showing
2 changed files
with
37 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
/// Either an instance of `T` or the absence thereof. | ||
/// | ||
/// Use `Optional` when you need to represent a value that may or may not be present. | ||
public typealias Optional<T> = Union<T, None<T>> | ||
|
||
/// The absence of an instance of `T`. | ||
public type None<T> { | ||
|
||
/// Creates a value denoting the absence of an instance of `T`. | ||
public memberwise init | ||
|
||
} | ||
|
||
public conformance None: Regular { | ||
|
||
// TODO: Remove when #1078 is implemented. | ||
public fun copy() -> Self { | ||
None() | ||
} | ||
|
||
// TODO: Remove when #1078 is implemented. | ||
public fun infix==(_ other: Self) -> Bool { | ||
true | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
//- compileAndRun expecting: success | ||
|
||
public fun main() { | ||
var x: Optional<Int> = 42 | ||
let y = if let i: Int = x { i.copy() } else { 0 } | ||
precondition(y == 42) | ||
|
||
&x = None() | ||
let z = if let i: Int = x { i.copy() } else { 0 } | ||
precondition(z == 0) | ||
} |