summaryrefslogtreecommitdiff
path: root/src/util/maybe.h
blob: c3247d30738c975b5e9a95f9d03ca7eea2b726ae (plain)
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
/*********************                                                        */
/*! \file maybe.h
 ** \verbatim
 ** Top contributors (to current version):
 **   Tim King
 ** This file is part of the CVC4 project.
 ** Copyright (c) 2009-2019 by the authors listed in the file AUTHORS
 ** in the top-level source directory) and their institutional affiliations.
 ** All rights reserved.  See the file COPYING in the top-level source
 ** directory for licensing information.\endverbatim
 **
 ** \brief This provides a templated Maybe construct.
 **
 ** This class provides a templated Maybe<T> construct.
 ** This follows the rough pattern of the Maybe monad in haskell.
 ** A Maybe is an algebraic type that is either Nothing | Just T
 **
 ** T must support T() and operator=.
 **
 ** This has a couple of uses:
 ** - There is no reasonable value or particularly clean way to represent
 **   Nothing using a value of T
 ** - High level of assurance that a value is not used before it is set.
 **/
#include "cvc4_public.h"

#ifndef __CVC4__UTIL__MAYBE_H
#define __CVC4__UTIL__MAYBE_H

#include <ostream>

#include "base/exception.h"

namespace CVC4 {

template <class T>
class CVC4_PUBLIC Maybe
{
 public:
  Maybe() : d_just(false), d_value(){}
  Maybe(const T& val): d_just(true), d_value(val){}

  Maybe& operator=(const T& v){
    d_just = true;
    d_value = v;
    return *this;
  }

  inline bool nothing() const { return !d_just; }
  inline bool just() const { return d_just; }
  explicit operator bool() const noexcept { return just(); }

  void clear() {
    if(just()){
      d_just = false;
      d_value = T();
    }
  }

  const T& value() const
  {
    if (nothing())
    {
      throw Exception("Maybe::value() requires the maybe to be set.");
    }
    return d_value;
  }

 private:
  bool d_just;
  T d_value;
};

template <class T>
inline std::ostream& operator<<(std::ostream& out, const Maybe<T>& m){
  out << "{";
  if(m.nothing()){
    out << "Nothing";
  }else{
    out << "Just ";
    out << m.value();
  }
  out << "}";
  return out;
}

}/* CVC4 namespace */

#endif /* __CVC4__UTIL__MAYBE_H */
generated by cgit on debian on lair
contact matthew@masot.net with questions or feedback