raskell 0.1.1

Haskell-style functional programming for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
//! Implementation details of [`hdo!`](crate::hdo).
//!
//! Nothing in this module is covered by semantic versioning. It is public only
//! because macro expansion has to name it.

/// A value produced by `pure`, waiting to be lifted into the surrounding monad.
pub struct Pure<T>(pub T);

/// A block tail that can become an [`Option`].
#[diagnostic::on_unimplemented(
    message = "`{Self}` cannot be used as the rest of an `Option` block in `hdo!`",
    label = "expected `Option` or `pure`",
    note = "every statement after an `Option` bind must produce `Option` or end in `pure`"
)]
pub trait OptionContinuation {
    /// The value carried by the resulting `Option`.
    type Value;

    /// Lifts the continuation into an `Option`.
    fn into_option(self) -> Option<Self::Value>;
}

impl<T> OptionContinuation for Pure<T> {
    type Value = T;

    fn into_option(self) -> Option<T> {
        Some(self.0)
    }
}

impl<T> OptionContinuation for Option<T> {
    type Value = T;

    fn into_option(self) -> Option<T> {
        self
    }
}

/// A block tail that can become a [`Result`] with error type `E`.
#[diagnostic::on_unimplemented(
    message = "`{Self}` cannot be used as the rest of a `Result` block in `hdo!`",
    label = "expected `Result<_, {E}>` or `pure`",
    note = "`guard condition;` produces `Option`; inside a `Result` block write \
            `guard condition throw MyError;`",
    note = "to bind a `Result` with a different error type, use `<-?`, which \
            converts through `From`"
)]
pub trait ResultContinuation<E> {
    /// The value carried by the resulting `Result`.
    type Value;

    /// Lifts the continuation into a `Result`.
    fn into_result(self) -> Result<Self::Value, E>;
}

impl<T, E> ResultContinuation<E> for Pure<T> {
    type Value = T;

    fn into_result(self) -> Result<T, E> {
        Ok(self.0)
    }
}

impl<T, E> ResultContinuation<E> for Result<T, E> {
    type Value = T;

    fn into_result(self) -> Result<T, E> {
        self
    }
}

/// A block tail that can become a list.
///
/// [`Option`] counts as a list of zero or one elements, which is what makes
/// `guard` usable inside list blocks.
#[diagnostic::on_unimplemented(
    message = "`{Self}` cannot be used as the rest of a list block in `hdo!`",
    label = "expected `Vec`, `Option` or `pure`"
)]
pub trait ListContinuation {
    /// The element type of the resulting list.
    type Value;

    /// Lifts the continuation into a `Vec`.
    fn into_list(self) -> Vec<Self::Value>;
}

impl<T> ListContinuation for Pure<T> {
    type Value = T;

    fn into_list(self) -> Vec<T> {
        ::std::vec![self.0]
    }
}

impl<T> ListContinuation for Vec<T> {
    type Value = T;

    fn into_list(self) -> Vec<T> {
        self
    }
}

impl<T> ListContinuation for Option<T> {
    type Value = T;

    fn into_list(self) -> Vec<T> {
        self.into_iter().collect()
    }
}

/// Sequencing of `pattern <- expression;`.
#[diagnostic::on_unimplemented(
    message = "`{Self}` is not a monad supported by `hdo!`",
    label = "cannot bind this with `<-`",
    note = "`hdo!` binds `Option`, `Result` and `Vec`"
)]
pub trait HdoBind<F> {
    /// The type of the whole block.
    type Output;

    /// Runs `next` on the bound value, short-circuiting on failure.
    fn hdo_bind(self, next: F) -> Self::Output;
}

impl<T, F, C> HdoBind<F> for Option<T>
where
    F: FnOnce(T) -> C,
    C: OptionContinuation,
{
    type Output = Option<C::Value>;

    fn hdo_bind(self, next: F) -> Self::Output {
        self.and_then(|value| next(value).into_option())
    }
}

impl<T, E, F, C> HdoBind<F> for Result<T, E>
where
    F: FnOnce(T) -> C,
    C: ResultContinuation<E>,
{
    type Output = Result<C::Value, E>;

    fn hdo_bind(self, next: F) -> Self::Output {
        self.and_then(|value| next(value).into_result())
    }
}

impl<T, F, C> HdoBind<F> for Vec<T>
where
    F: FnMut(T) -> C,
    C: ListContinuation,
{
    type Output = Vec<C::Value>;

    fn hdo_bind(self, mut next: F) -> Self::Output {
        self.into_iter()
            .flat_map(|value| next(value).into_list())
            .collect()
    }
}

/// Sequencing of a bare statement expression, such as `validate()?`-style actions.
#[diagnostic::on_unimplemented(
    message = "`{Self}` cannot be used as a statement inside `hdo!`",
    label = "this action is neither `()` nor a supported monad",
    note = "bind it with `<-` instead, or discard it with `let _ = ...;`"
)]
pub trait HdoThen<F> {
    /// The type of the whole block.
    type Output;

    /// Runs `next`, short-circuiting if `self` already failed.
    fn hdo_then(self, next: F) -> Self::Output;
}

impl<F, C> HdoThen<F> for ()
where
    F: FnOnce() -> C,
{
    type Output = C;

    fn hdo_then(self, next: F) -> Self::Output {
        next()
    }
}

impl<T, F, C> HdoThen<F> for Option<T>
where
    F: FnOnce() -> C,
    C: OptionContinuation,
{
    type Output = Option<C::Value>;

    fn hdo_then(self, next: F) -> Self::Output {
        self.and_then(|_| next().into_option())
    }
}

impl<T, E, F, C> HdoThen<F> for Result<T, E>
where
    F: FnOnce() -> C,
    C: ResultContinuation<E>,
{
    type Output = Result<C::Value, E>;

    fn hdo_then(self, next: F) -> Self::Output {
        self.and_then(|_| next().into_result())
    }
}

impl<T, F, C> HdoThen<F> for Vec<T>
where
    F: FnMut() -> C,
    C: ListContinuation,
{
    type Output = Vec<C::Value>;

    fn hdo_then(self, mut next: F) -> Self::Output {
        self.into_iter().flat_map(|_| next().into_list()).collect()
    }
}

/// Expansion of `guard condition;`.
pub fn guard_option<C>(condition: bool, next: impl FnOnce() -> C) -> Option<C::Value>
where
    C: OptionContinuation,
{
    if condition {
        next().into_option()
    } else {
        None
    }
}

/// Expansion of `guard condition throw error;`.
pub fn guard_result<C, E>(
    condition: bool,
    error: E,
    next: impl FnOnce() -> C,
) -> Result<C::Value, E>
where
    C: ResultContinuation<E>,
{
    if condition {
        next().into_result()
    } else {
        Err(error)
    }
}

/// Unwraps a block that never bound anything monadic.
#[diagnostic::on_unimplemented(
    message = "`{Self}` is not a valid result for an `hdo!` block",
    label = "this block does not produce `Option`, `Result` or `Vec`"
)]
pub trait HdoFinish {
    /// The type of the whole block.
    type Output;

    /// Returns the block's value.
    fn hdo_finish(self) -> Self::Output;
}

impl<T> HdoFinish for Pure<T> {
    type Output = T;

    fn hdo_finish(self) -> T {
        self.0
    }
}

impl<T> HdoFinish for Option<T> {
    type Output = Option<T>;

    fn hdo_finish(self) -> Self::Output {
        self
    }
}

impl<T, E> HdoFinish for Result<T, E> {
    type Output = Result<T, E>;

    fn hdo_finish(self) -> Self::Output {
        self
    }
}

impl<T> HdoFinish for Vec<T> {
    type Output = Vec<T>;

    fn hdo_finish(self) -> Self::Output {
        self
    }
}

/// Sequencing of a refutable pattern bind without `throw`.
#[diagnostic::on_unimplemented(
    message = "refutable pattern without `throw` is only supported for `Option` in `hdo!`",
    label = "this bind needs an explicit failure value",
    note = "for `Result`, use `pattern <- expression throw YourError;`"
)]
pub trait HdoPatternBind<F> {
    /// The type of the whole block.
    type Output;

    /// Runs `next`, which yields `None` when the pattern does not match.
    fn hdo_pattern_bind(self, next: F) -> Self::Output;
}

#[diagnostic::do_not_recommend]
impl<T, F, U> HdoPatternBind<F> for Option<T>
where
    F: FnOnce(T) -> Option<U>,
{
    type Output = Option<U>;

    fn hdo_pattern_bind(self, next: F) -> Self::Output {
        self.and_then(next)
    }
}

/// The residual of a `None`, kept distinct from any user error type.
pub struct NoneResidual;

/// Builds a short-circuited block result from a failed step's residual.
#[diagnostic::on_unimplemented(
    message = "`{Self}` cannot short-circuit on `{Residual}`",
    label = "the block's type and the bound value's failure do not match",
    note = "an `Option` bind needs an `Option` block; a `Result<_, E>` bind needs \
            a `Result<_, E>` block, or `<-?` to convert the error"
)]
pub trait HdoShortCircuit<Residual> {
    /// Produces the value the block returns when a step fails.
    fn hdo_short_circuit(residual: Residual) -> Self;
}

impl<T> HdoShortCircuit<NoneResidual> for Option<T> {
    fn hdo_short_circuit(_: NoneResidual) -> Self {
        None
    }
}

impl<T, E> HdoShortCircuit<E> for Result<T, E> {
    fn hdo_short_circuit(residual: E) -> Self {
        Err(residual)
    }
}

/// Wraps a `pure` value into the block's type.
#[diagnostic::on_unimplemented(
    message = "`{Self}` is not a monad that `pure` can produce",
    label = "expected `Option` or `Result`",
    note = "annotate the awaited block, for example `let x: Result<_, MyError> = block.await;`"
)]
pub trait HdoPure<T> {
    /// Lifts `value` into the block's type.
    fn hdo_pure(value: T) -> Self;
}

impl<T> HdoPure<T> for Option<T> {
    fn hdo_pure(value: T) -> Self {
        Some(value)
    }
}

impl<T, E> HdoPure<T> for Result<T, E> {
    fn hdo_pure(value: T) -> Self {
        Ok(value)
    }
}

/// Sequencing of `pattern <- expression;` inside `hdo!(async { .. })`.
///
/// Unlike the synchronous [`HdoBind`], this never takes a continuation closure,
/// which is what lets the rest of the block contain `.await`.
#[diagnostic::on_unimplemented(
    message = "`{Self}` cannot be bound with `<-` inside an `hdo!` async block",
    label = "expected `Option` or `Result`",
    note = "an `hdo!` async block binds `Option` and `Result`; lists have no short-circuiting form",
    note = "to await a future, write the `.await` yourself: `x <- fetch().await;`"
)]
pub trait HdoAsyncBind<B> {
    /// The bound value.
    type Value;

    /// Either yields the bound value or the block's short-circuited result.
    fn hdo_async_bind(self) -> ::core::ops::ControlFlow<B, Self::Value>;
}

impl<T, B> HdoAsyncBind<B> for Option<T>
where
    B: HdoShortCircuit<NoneResidual>,
{
    type Value = T;

    fn hdo_async_bind(self) -> ::core::ops::ControlFlow<B, T> {
        match self {
            Some(value) => ::core::ops::ControlFlow::Continue(value),
            None => ::core::ops::ControlFlow::Break(B::hdo_short_circuit(NoneResidual)),
        }
    }
}

impl<T, E, B> HdoAsyncBind<B> for Result<T, E>
where
    B: HdoShortCircuit<E>,
{
    type Value = T;

    fn hdo_async_bind(self) -> ::core::ops::ControlFlow<B, T> {
        match self {
            Ok(value) => ::core::ops::ControlFlow::Continue(value),
            Err(error) => ::core::ops::ControlFlow::Break(B::hdo_short_circuit(error)),
        }
    }
}

/// Sequencing of a bare statement expression inside `hdo!(async { .. })`.
#[diagnostic::on_unimplemented(
    message = "`{Self}` cannot be used as a statement inside an `hdo!` async block",
    label = "this action is neither `()` nor `Option` nor `Result`",
    note = "bind it with `<-` instead, or discard it with `let _ = ...;`"
)]
pub trait HdoAsyncAction<B> {
    /// Either continues the block or short-circuits it.
    fn hdo_async_action(self) -> ::core::ops::ControlFlow<B, ()>;
}

impl<B> HdoAsyncAction<B> for () {
    fn hdo_async_action(self) -> ::core::ops::ControlFlow<B, ()> {
        ::core::ops::ControlFlow::Continue(())
    }
}

impl<T, B> HdoAsyncAction<B> for Option<T>
where
    B: HdoShortCircuit<NoneResidual>,
{
    fn hdo_async_action(self) -> ::core::ops::ControlFlow<B, ()> {
        match self {
            Some(_) => ::core::ops::ControlFlow::Continue(()),
            None => ::core::ops::ControlFlow::Break(B::hdo_short_circuit(NoneResidual)),
        }
    }
}

impl<T, E, B> HdoAsyncAction<B> for Result<T, E>
where
    B: HdoShortCircuit<E>,
{
    fn hdo_async_action(self) -> ::core::ops::ControlFlow<B, ()> {
        match self {
            Ok(_) => ::core::ops::ControlFlow::Continue(()),
            Err(error) => ::core::ops::ControlFlow::Break(B::hdo_short_circuit(error)),
        }
    }
}