1 |
|
/****************************************************************************** |
2 |
|
* Top contributors (to current version): |
3 |
|
* Tim King, Mathias Preiner |
4 |
|
* |
5 |
|
* This file is part of the cvc5 project. |
6 |
|
* |
7 |
|
* Copyright (c) 2009-2021 by the authors listed in the file AUTHORS |
8 |
|
* in the top-level source directory and their institutional affiliations. |
9 |
|
* All rights reserved. See the file COPYING in the top-level source |
10 |
|
* directory for licensing information. |
11 |
|
* **************************************************************************** |
12 |
|
* |
13 |
|
* This provides a templated Maybe construct. |
14 |
|
* |
15 |
|
* This class provides a templated Maybe<T> construct. |
16 |
|
* This follows the rough pattern of the Maybe monad in haskell. |
17 |
|
* A Maybe is an algebraic type that is either Nothing | Just T |
18 |
|
* |
19 |
|
* T must support T() and operator=. |
20 |
|
* |
21 |
|
* This has a couple of uses: |
22 |
|
* - There is no reasonable value or particularly clean way to represent |
23 |
|
* Nothing using a value of T |
24 |
|
* - High level of assurance that a value is not used before it is set. |
25 |
|
*/ |
26 |
|
#include "cvc5_public.h" |
27 |
|
|
28 |
|
#ifndef CVC5__UTIL__MAYBE_H |
29 |
|
#define CVC5__UTIL__MAYBE_H |
30 |
|
|
31 |
|
#include <ostream> |
32 |
|
|
33 |
|
#include "base/exception.h" |
34 |
|
|
35 |
|
namespace cvc5 { |
36 |
|
|
37 |
|
template <class T> |
38 |
29593 |
class Maybe |
39 |
|
{ |
40 |
|
public: |
41 |
42751 |
Maybe() : d_just(false), d_value(){} |
42 |
14 |
Maybe(const T& val): d_just(true), d_value(val){} |
43 |
|
|
44 |
4 |
Maybe& operator=(const T& v){ |
45 |
4 |
d_just = true; |
46 |
4 |
d_value = v; |
47 |
4 |
return *this; |
48 |
|
} |
49 |
|
|
50 |
22 |
inline bool nothing() const { return !d_just; } |
51 |
26 |
inline bool just() const { return d_just; } |
52 |
24 |
explicit operator bool() const noexcept { return just(); } |
53 |
|
|
54 |
2 |
void clear() { |
55 |
2 |
if(just()){ |
56 |
|
d_just = false; |
57 |
|
d_value = T(); |
58 |
|
} |
59 |
2 |
} |
60 |
|
|
61 |
22 |
const T& value() const |
62 |
|
{ |
63 |
22 |
if (nothing()) |
64 |
|
{ |
65 |
|
throw Exception("Maybe::value() requires the maybe to be set."); |
66 |
|
} |
67 |
22 |
return d_value; |
68 |
|
} |
69 |
|
|
70 |
|
private: |
71 |
|
bool d_just; |
72 |
|
T d_value; |
73 |
|
}; |
74 |
|
|
75 |
|
template <class T> |
76 |
|
inline std::ostream& operator<<(std::ostream& out, const Maybe<T>& m){ |
77 |
|
out << "{"; |
78 |
|
if(m.nothing()){ |
79 |
|
out << "Nothing"; |
80 |
|
}else{ |
81 |
|
out << "Just "; |
82 |
|
out << m.value(); |
83 |
|
} |
84 |
|
out << "}"; |
85 |
|
return out; |
86 |
|
} |
87 |
|
|
88 |
|
} // namespace cvc5 |
89 |
|
|
90 |
|
#endif /* CVC5__UTIL__MAYBE_H */ |