Advertisement
Guest User

Untitled

a guest
Oct 4th, 2015
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. #lang racket
  2.  
  3. (require rackunit)
  4.  
  5. (provide Nothing Just Maybe whenJust orElse)
  6.  
  7. (define (Nothing)
  8. (lambda () #f))
  9.  
  10. (define (Just a)
  11. (lambda () a))
  12.  
  13. (let ([maybeA (Nothing)]
  14. [maybeB (Just 10)])
  15. (check-equal? (maybeB) 10)
  16. (check-equal? (maybeA) #f))
  17.  
  18. (define (Maybe default fun maybe)
  19. (if (equal? Nothing maybe)
  20. default
  21. (fun (maybe))))
  22.  
  23. (check-equal? (Maybe #f odd? (Just 3)) #t)
  24. (check-equal? (Maybe #f odd? Nothing) #f)
  25. (check-equal? (Maybe 0 + (Just 10)) 10)
  26. (check-equal? (Maybe 0 + Nothing) 0)
  27.  
  28. (define (whenJust f maybe)
  29. (if (equal? Nothing maybe)
  30. maybe
  31. (Just (f (maybe)))))
  32.  
  33. (define (add-five n)
  34. (+ n 5))
  35.  
  36. (check-equal? (whenJust add-five Nothing) Nothing)
  37. (check-equal? ((whenJust add-five (Just 10))) 15)
  38. (check-equal? ((whenJust add-five
  39. (whenJust add-five (Just 10))))
  40. 20)
  41. (check-equal? (whenJust add-five
  42. (whenJust add-five Nothing))
  43. Nothing)
  44.  
  45. (define (orElse b maybe)
  46. (if (equal? Nothing maybe)
  47. b
  48. (maybe)))
  49.  
  50. (check-equal? (orElse 10 Nothing) 10)
  51. (check-equal? (orElse 5 (Just 10)) 10)
  52.  
  53. (define (safeDivide a b)
  54. (if (zero? b)
  55. Nothing
  56. (Just (/ a b))))
  57.  
  58. (check-equal? (safeDivide 10 0) Nothing)
  59. (check-equal? ((safeDivide 10 2)) 5)
  60. (check-equal? (orElse 0 (safeDivide 10 0)) 0)
  61. (check-equal? (orElse 0 (safeDivide 10 2)) 5)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement