Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 23 additions & 8 deletions stdlib/option.affine
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@
module option;

// `Option`/`Result` types + constructors are owned by `prelude` (ADR-011).
use prelude::{Option, Some, None, Result, Ok, Err, map};
// `map` is defined locally below as the Option map (f, Option<T>);
// it is NOT imported from prelude (prelude's `map` is the list map
// with a different signature — importing both would conflict).
use prelude::{Option, Some, None, Result, Ok, Err};

// This module is the single canonical home for the Option *operations*
// (is_some/is_none/unwrap/unwrap_or/map/filter/contains/…). #133 removed
Expand Down Expand Up @@ -184,14 +187,20 @@ fn unzip<A, B>(opt: Option<(A, B)>) -> (Option<A>, Option<B>) {
/// Transpose Option of list to list of Option
fn transpose<T>(opt: Option<[T]>) -> [Option<T>] {
match opt {
Some(list) => map(fn(x) => Some(x), list),
Some(list) => {
let mut result = [];
for x in list {
result = result ++ [Some(x)];
}
result
},
None => []
}
}

/// Collect list of Options into Option of list (None on any None)
fn collect<T>(opts: [Option<T>]) -> Option<[T]> {
let values = [];
let mut values = [];
for opt in opts {
match opt {
Some(value) => values = values ++ [value],
Expand All @@ -203,10 +212,13 @@ fn collect<T>(opts: [Option<T>]) -> Option<[T]> {

/// Filter out Nones from list
fn cat_options<T>(opts: [Option<T>]) -> [T] {
let values = [];
let mut values = [];
for opt in opts {
match opt {
Some(value) => values = values ++ [value],
// Statement-block arm so the arm is Unit-typed and matches the
// `None => {}` arm (a bare assignment expression is typed as its
// RHS, which would clash Array vs Unit across the arms).
Some(value) => { values = values ++ [value]; },
None => {}
}
}
Expand All @@ -215,7 +227,10 @@ fn cat_options<T>(opts: [Option<T>]) -> [T] {

/// Map list with function returning Option, filtering Nones
fn map_filter<T, U>(f: T -> Option<U>, list: [T]) -> [U] {
let results = map(f, list);
let mut results = [];
for x in list {
results = results ++ [f(x)];
}
cat_options(results)
}

Expand Down Expand Up @@ -317,14 +332,14 @@ fn replace_none<T>(opt: Option<T>, replacement: Option<T>) -> Option<T> {
}

/// Take value from Option, leaving None
fn take<T>(opt: &mut Option<T>) -> Option<T> {
fn take<T>(mut opt: Option<T>) -> Option<T> {
let result = opt;
opt = None;
result
}

/// Insert value into Option if None
fn get_or_insert<T>(opt: &mut Option<T>, value: T) -> T {
fn get_or_insert<T>(mut opt: Option<T>, value: T) -> T {
match opt {
Some(x) => x,
None => {
Expand Down
Loading