/
exceptional.lean
54 lines (44 loc) · 1.58 KB
/
exceptional.lean
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
/-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.control.monad init.meta.format init.util
/-
Remark: we use a function that produces a format object as the exception information.
Motivation: the formatting object may be big, and we may create it on demand.
-/
/-- An exceptional is similar to `Result` in Haskell.-/
meta inductive exceptional (α : Type)
| success : α → exceptional
| exception : (options → format) → exceptional
section
open exceptional
variables {α : Type}
variables [has_to_string α]
protected meta def exceptional.to_string : exceptional α → string
| (success a) := to_string a
| (exception e) := "Exception: " ++ to_string (e options.mk)
meta instance : has_to_string (exceptional α) :=
has_to_string.mk exceptional.to_string
end
namespace exceptional
variables {α β : Type}
protected meta def to_bool : exceptional α → bool
| (success _) := tt
| (exception _) := ff
protected meta def to_option : exceptional α → option α
| (success a) := some a
| (exception _) := none
@[inline] protected meta def bind (e₁ : exceptional α) (e₂ : α → exceptional β) : exceptional β :=
exceptional.cases_on e₁
(λ a, e₂ a)
(λ f, exception f)
@[inline] protected meta def return (a : α) : exceptional α :=
success a
@[inline] meta def fail (f : format) : exceptional α :=
exception (λ u, f)
end exceptional
meta instance : monad exceptional :=
{pure := @exceptional.return, bind := @exceptional.bind}