LispBoolean.java 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package migl.lisp;
  2. /**
  3. * Simple Boolean type for our lisp interpreter.
  4. *
  5. * We do not use the classical boolean operators in order to have an easy
  6. * translation to and from the lisp representation of Booleans.
  7. *
  8. * The Boolean operators are not implemented. They must be applied on the
  9. * {@link #value()} of the object.
  10. *
  11. * @author leberre
  12. *
  13. */
  14. public final class LispBoolean {
  15. /**
  16. * The object representing the true Boolean value.
  17. */
  18. public static final LispBoolean TRUE = new LispBoolean(true);
  19. /**
  20. * The object representing the false Boolean value.
  21. */
  22. public static final LispBoolean FALSE = new LispBoolean(false);
  23. private final boolean value;
  24. private LispBoolean(boolean value) {
  25. this.value = value;
  26. }
  27. /**
  28. * Retrieve a Java primitive Boolean value for Boolean reasoning in Java code.
  29. *
  30. * @return the corresponding Java's Boolean value.
  31. */
  32. public boolean value() {
  33. return this.value;
  34. }
  35. @Override
  36. public int hashCode() {
  37. return Boolean.hashCode(value);
  38. }
  39. @Override
  40. public boolean equals(Object obj) {
  41. if (obj instanceof LispBoolean) {
  42. return ((LispBoolean) obj).value == value;
  43. }
  44. return false;
  45. }
  46. @Override
  47. public String toString() {
  48. return value ? "#t" : "#f";
  49. }
  50. /**
  51. * Retrieve a {@link LispBoolean} from a Java primitive Boolean.
  52. *
  53. * @param b
  54. * a Boolean value
  55. * @return the corresponding {@link LispBoolean} object.
  56. */
  57. public static LispBoolean valueOf(boolean b) {
  58. return b ? TRUE : FALSE;
  59. }
  60. /**
  61. * Retrieve a {@link LispBoolean} from its textual representation.
  62. *
  63. * @param s
  64. * a textual representation of the boolean value (#t or #f)
  65. * @return the corresponding {@link LispBoolean} object.
  66. * @throws IllegalArgumentException
  67. * if s does not correspond to a valid textual representation.
  68. */
  69. public static LispBoolean valueOf(String s) {
  70. switch (s.toLowerCase()) {
  71. case "#t":
  72. return TRUE;
  73. case "#f":
  74. return FALSE;
  75. default:
  76. throw new IllegalArgumentException("Not a Boolean");
  77. }
  78. }
  79. }