Guest User

Untitled

a guest
Jul 23rd, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. package pbt;
  2.  
  3. import static org.junit.Assert.assertEquals;
  4. import static pbt.MonoidTest.Balance.ERROR;
  5. import static pbt.MonoidTest.Balance.ZERO;
  6.  
  7. import org.junit.runner.RunWith;
  8.  
  9. import com.pholser.junit.quickcheck.From;
  10. import com.pholser.junit.quickcheck.Property;
  11. import com.pholser.junit.quickcheck.generator.Ctor;
  12. import com.pholser.junit.quickcheck.runner.JUnitQuickcheck;
  13.  
  14. @RunWith(JUnitQuickcheck.class)
  15. public class MonoidTest {
  16.  
  17. @Property
  18. public void neutralElement(@From(Ctor.class) Balance a) {
  19. assertEquals(a.add(ZERO), a);
  20. assertEquals(ZERO.add(a), a);
  21. }
  22.  
  23. @Property
  24. public void associativity(@From(Ctor.class) Balance a, @From(Ctor.class) Balance b, @From(Ctor.class) Balance c) {
  25. assertEquals(a.add(b).add(c), a.add(b.add(c)));
  26. }
  27.  
  28. // This particular monoid happens to be commutative
  29. @Property
  30. public void commutativity(@From(Ctor.class) Balance a, @From(Ctor.class) Balance b) {
  31. assertEquals(a.add(b), b.add(a));
  32. }
  33.  
  34. @Property
  35. public void errorIsAbsorbingElement(@From(Ctor.class) Balance a) {
  36. assertEquals(a.add(ERROR), ERROR);
  37. assertEquals(ERROR.add(a), ERROR);
  38. }
  39.  
  40. public static class Balance {
  41.  
  42. // the nominal value of the balance
  43. private final int balance;
  44.  
  45. // marks this instance as an error
  46. private final boolean error;
  47.  
  48. // neutral element
  49. public final static Balance ZERO = new Balance(0);
  50.  
  51. // error element, is absorbing element
  52. public final static Balance ERROR = new Balance(0, true);
  53.  
  54. public Balance(int balance) {
  55. this(balance, false);
  56. }
  57.  
  58. private Balance(int balance, boolean error) {
  59. this.balance = balance;
  60. this.error = error;
  61. }
  62.  
  63. public boolean isError() {
  64. return error;
  65. }
  66.  
  67. public Balance add(Balance other) {
  68. return error ? ERROR : other.error ? ERROR : new Balance(balance + other.balance);
  69. }
  70.  
  71. @Override
  72. public int hashCode() {
  73. return (int) (31 ^ balance);
  74. }
  75.  
  76. @Override
  77. public boolean equals(Object o) {
  78. Balance other = (Balance) o;
  79. return balance == other.balance && error == other.error;
  80. }
  81.  
  82. @Override
  83. public String toString() {
  84. return error ? "ERROR" : balance + "";
  85. }
  86.  
  87. }
  88.  
  89. }
Add Comment
Please, Sign In to add comment