Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use expressions #352

Merged
merged 6 commits into from
Sep 28, 2023
Merged
Show file tree
Hide file tree
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
8 changes: 8 additions & 0 deletions concepts/use-expressions/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"blurb": "Gleam's use expression syntax makes working with nested callbacks easier and more readable.",
"authors": [
"lpil"
],
"contributors": [
]
}
70 changes: 70 additions & 0 deletions concepts/use-expressions/about.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# About

In Gleam it is common to write and use higher order functions, that is functions that take other functions as arguments. Sometimes when using many higher order functions at once the code can become difficult to read, with many layers of indentation.

For example, here is a function that calls several functions that return `Result(Int, Nil)`, and sums the values if all four are successful.

```gleam
import gleam/result

pub fn main() -> Result(Int, Nil) {
result.try(function1(), fn(a) {
result.try(function2(), fn(b) {
result.try(function3(), fn(c) {
result.try(function4(), fn(d) {
Ok(a + b + c + d)
})
})
})
})
}
```

Gleam's `use` expressions allow us to write this code without the indentation, often making it easier to read.

```gleam
import gleam/result

pub fn main() -> Result(Int, Nil) {
use a <- result.try(function1())
use b <- result.try(function2())
use c <- result.try(function3())
use d <- result.try(function4())
Ok(a + b + c + d)
}
```

A `use` expression collects all the following statements in the block and passes it as a callback function as the final argument to the function call. The variables between the `use` keyword and the `<-` symbol are the names of the arguments that will be passed to the callback function.

```gleam
// This use expression
use a <- function(1, 2)
io.println("Hello!")
a

// Is equivalent to this normal function call
function(1, 2, fn(a) {
io.println("Hello!")
a
})
```

The callback function can take any number of arguments, or none at all.

```gleam
use a, b, c, d <- call_4_function()

use <- call_0_function()
```

There are no special requirements to create a function that can be called with a `use` expression, other than taking a callback function as the final argument.

```gleam
pub fn call_twice(function: fn() -> t) -> #(t, t) {
let first = function()
let second = function()
#(first, second)
}
```

Gleam's `use` expressions are a very powerful feature that can be applied to lots of problems, but when overused they can make code difficult to read. It is generally preferred to use the normal function call syntax and only reach for `use` expressions when they make the code easier to read.
70 changes: 70 additions & 0 deletions concepts/use-expressions/introduction.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# Introduction

In Gleam it is common to write and use higher order functions, that is functions that take other functions as arguments. Sometimes when using many higher order functions at once the code can become difficult to read, with many layers of indentation.

For example, here is a function that calls several functions that return `Result(Int, Nil)`, and sums the values if all four are successful.

```gleam
import gleam/result

pub fn main() -> Result(Int, Nil) {
result.try(function1(), fn(a) {
result.try(function2(), fn(b) {
result.try(function3(), fn(c) {
result.try(function4(), fn(d) {
Ok(a + b + c + d)
})
})
})
})
}
```

Gleam's `use` expressions allow us to write this code without the indentation, often making it easier to read.

```gleam
import gleam/result

pub fn main() -> Result(Int, Nil) {
use a <- result.try(function1())
use b <- result.try(function2())
use c <- result.try(function3())
use d <- result.try(function4())
Ok(a + b + c + d)
}
```

A `use` expression collects all the following statements in the block and passes it as a callback function as the final argument to the function call. The variables between the `use` keyword and the `<-` symbol are the names of the arguments that will be passed to the callback function.

```gleam
// This use expression
use a <- function(1, 2)
io.println("Hello!")
a

// Is equivalent to this normal function call
function(1, 2, fn(a) {
io.println("Hello!")
a
})
```

The callback function can take any number of arguments, or none at all.

```gleam
use a, b, c, d <- call_4_function()

use <- call_0_function()
```

There are no special requirements to create a function that can be called with a `use` expression, other than taking a callback function as the final argument.

```gleam
pub fn call_twice(function: fn() -> t) -> #(t, t) {
let first = function()
let second = function()
#(first, second)
}
```

Gleam's `use` expressions are a very powerful feature that can be applied to lots of problems, but when overused they can make code difficult to read. It is generally preferred to use the normal function call syntax and only reach for `use` expressions when they make the code easier to read.
2 changes: 2 additions & 0 deletions concepts/use-expressions/links.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[
]
18 changes: 18 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,19 @@
"maps"
],
"status": "active"
},
{
"slug": "expert-experiments",
"name": "Expert Experiments",
"uuid": "481133be-f550-4639-8e26-4f03fe292d1c",
"concepts": [
"use-expressions"
],
"prerequisites": [
"results",
"anonymous-functions"
],
"status": "active"
}
],
"practice": [
Expand Down Expand Up @@ -1999,6 +2012,11 @@
"uuid": "6b3a8671-4fef-4e72-ab58-2fc12893d9ae",
"slug": "external-types",
"name": "External Types"
},
{
"uuid": "e33cc76d-a5c5-47cb-ab91-aa1f2da988b9",
"slug": "use-expressions",
"name": "Use Expressions"
}
],
"key_features": [
Expand Down
15 changes: 15 additions & 0 deletions exercises/concept/expert-experiments/.docs/hints.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Hints

## 1. Define the `with_retry` function

- A `case` expression can be used to pattern match on a result.

## 2. Define the `record_timing` function

- The `time_logger` function should be called even if the `experiment` function returns an `Error` value.

## 3. Define the `run_experiment` function

- The [`result.try` function][result-try] can be used in a `use` expression to stop if a result is an `Error` value.

[result-try]: https://hexdocs.pm/gleam_stdlib/gleam/result.html#try
64 changes: 64 additions & 0 deletions exercises/concept/expert-experiments/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# Instructions

Daphne has been working on a system to run and record the results of her experiments. Some of the code has become a bit verbose and repetitive, so she's asked you to write some `use` expressions to help clean it up.

## 1. Define the `with_retry` function

Sometimes experiments can fail due to a one-off mistake, so if an experiment fails Daphne wants to retry it again to see if it works the second time.

Define the `with_retry` function that takes a result returning function as an argument.

If the function returns an `Ok` value then `with_retry` should return that value.

If the function returns an `Error` value then `with_retry` should call the function again and return the result of that call.

Daphne will use the function like this:

```gleam
pub fn main() {
use <- with_retry
// Perform the experiment here
}
```

## 2. Define the `record_timing` function

Daphne records how long each experiment takes to run by calling a time logging function before and after each experiment.

Define the `record_timing` function that takes two arguments:
- A time logging function which takes no arguments and returns `Nil`.
- An experiment function which takes no arguments and returns a result.

`record_timing` should call the time logging function, then call the experiment function, then call the time logging function again, and finally return the result of the experiment function.

Daphne will use the function like this:

```gleam
pub fn main() {
use <- record_timing(time_logger)
// Perform the experiment here
}
```

## 3. Define the `run_experiment` function

Experiments are made up of three phases. The setup, the action, and the recording. All three phases return results, and each phase needs the successful result of the previous phase to run.

Define the `run_experiment` function that takes four arguments:
- The name of the experiment as a `String`.
- A setup function which takes no arguments and returns a result.
- An action function which takes the `Ok` value of the setup function as an argument and returns a result.
- A recording function which takes the `Ok` value of the setup and functions as an arguments and returns a result.

If all three functions succeed then `run_experiment` should return `Ok(#(experiment_name, recording_data))`.

If any of the functions return an `Error` value then `run_experiment` should return that value.

Daphne will use the function like this:

```gleam
pub fn main() {
use setup_data, action_data <- run_experiment("Test 1", setup, action)
// Record the results here
}
```
72 changes: 72 additions & 0 deletions exercises/concept/expert-experiments/.docs/introduction.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# Introduction

## Use Expressions

In Gleam it is common to write and use higher order functions, that is functions that take other functions as arguments. Sometimes when using many higher order functions at once the code can become difficult to read, with many layers of indentation.

For example, here is a function that calls several functions that return `Result(Int, Nil)`, and sums the values if all four are successful.

```gleam
import gleam/result

pub fn main() -> Result(Int, Nil) {
result.try(function1(), fn(a) {
result.try(function2(), fn(b) {
result.try(function3(), fn(c) {
result.try(function4(), fn(d) {
Ok(a + b + c + d)
})
})
})
})
}
```

Gleam's `use` expressions allow us to write this code without the indentation, often making it easier to read.

```gleam
import gleam/result

pub fn main() -> Result(Int, Nil) {
use a <- result.try(function1())
use b <- result.try(function2())
use c <- result.try(function3())
use d <- result.try(function4())
Ok(a + b + c + d)
}
```

A `use` expression collects all the following statements in the block and passes it as a callback function as the final argument to the function call. The variables between the `use` keyword and the `<-` symbol are the names of the arguments that will be passed to the callback function.

```gleam
// This use expression
use a <- function(1, 2)
io.println("Hello!")
a

// Is equivalent to this normal function call
function(1, 2, fn(a) {
io.println("Hello!")
a
})
```

The callback function can take any number of arguments, or none at all.

```gleam
use a, b, c, d <- call_4_function()

use <- call_0_function()
```

There are no special requirements to create a function that can be called with a `use` expression, other than taking a callback function as the final argument.

```gleam
pub fn call_twice(function: fn() -> t) -> #(t, t) {
let first = function()
let second = function()
#(first, second)
}
```

Gleam's `use` expressions are a very powerful feature that can be applied to lots of problems, but when overused they can make code difficult to read. It is generally preferred to use the normal function call syntax and only reach for `use` expressions when they make the code easier to read.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Introduction

%{concept:use-expressions}
4 changes: 4 additions & 0 deletions exercises/concept/expert-experiments/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
*.beam
*.ez
build
erl_crash.dump
25 changes: 25 additions & 0 deletions exercises/concept/expert-experiments/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"authors": [
"lpil"
],
"contributors": [
],
"files": {
"solution": [
"src/expert_experiments.gleam"
],
"test": [
"test/expert_experiments_test.gleam"
],
"exemplar": [
".meta/example.gleam"
],
"invalidator": [
"gleam.toml",
"manifest.toml"
]
},
"forked_from": [
],
"blurb": "Learn about use expressions by conducting some experiments"
}
Loading
Loading