Last active
May 21, 2020 08:40
-
-
Save eterps/637520326c9561f9d988b1b1e3c9fc68 to your computer and use it in GitHub Desktop.
Testing the Option type in Gleam
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
import gleam/list | |
import gleam/result | |
import gleam/string | |
type PersonalName { | |
PersonalName( | |
first_name: String, | |
middle_initial: result.Option(String), | |
last_name: String, | |
) | |
}; | |
fn get_personal_names() -> List(PersonalName) { | |
[ | |
PersonalName( | |
first_name: "John", | |
middle_initial: result.none(), | |
last_name: "Doe", | |
), | |
PersonalName( | |
first_name: "Homer", | |
middle_initial: Ok("J"), | |
last_name: "Simpson", | |
), | |
] | |
} | |
fn to_label(name) -> String { | |
case name { | |
PersonalName( | |
first_name, | |
Error(Nil), | |
last_name, | |
) -> first_name | |
|> string.append(" ") | |
|> string.append(last_name) | |
PersonalName( | |
first_name, | |
Ok(middle_initial), | |
last_name, | |
) -> first_name | |
|> string.append(" ") | |
|> string.append(middle_initial) | |
|> string.append(". ") | |
|> string.append(last_name) | |
} | |
} | |
// => ["John Doe", "Homer J. Simpson"] | |
pub fn get_labelled_names() -> List(String) { | |
get_personal_names() | |
|> list.map(to_label) | |
} |
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
import gleam/list | |
import gleam/string | |
type Option(a) { | |
Some(a) | |
None | |
}; | |
type PersonalName { | |
PersonalName( | |
first_name: String, | |
middle_initial: Option(String), | |
last_name: String, | |
) | |
}; | |
fn get_personal_names() -> List(PersonalName) { | |
[ | |
PersonalName( | |
first_name: "John", | |
middle_initial: None, | |
last_name: "Doe", | |
), | |
PersonalName( | |
first_name: "Homer", | |
middle_initial: Some("J"), | |
last_name: "Simpson", | |
), | |
] | |
} | |
fn to_label(name) -> String { | |
case name { | |
PersonalName( | |
first_name, | |
None, | |
last_name, | |
) -> first_name | |
|> string.append(" ") | |
|> string.append(last_name) | |
PersonalName( | |
first_name, | |
Some(middle_initial), | |
last_name, | |
) -> first_name | |
|> string.append(" ") | |
|> string.append(middle_initial) | |
|> string.append(". ") | |
|> string.append(last_name) | |
} | |
} | |
// => ["John Doe", "Homer J. Simpson"] | |
pub fn get_labelled_names() -> List(String) { | |
get_personal_names() | |
|> list.map(to_label) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment