TestWith.agda 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. {-
  2. Agda Implementors' Meeting VI
  3. Göteborg
  4. May 24 - 30, 2007
  5. Hello Agda!
  6. Ulf Norell
  7. -}
  8. -- Something which is rather useful is the ability to pattern match
  9. -- on intermediate computations. That's where the with-construct comes
  10. -- in.
  11. module TestWith where
  12. -- open import Nat
  13. open import PreludeNat hiding(_==_; even; odd)
  14. open import PreludeShow
  15. {-
  16. Basic idea
  17. -}
  18. -- The basic principle is that you can add argument to your
  19. -- function on the fly. For instance,
  20. data Maybe (A : Set) : Set where
  21. nothing : Maybe A
  22. just : A -> Maybe A
  23. data _==_ {A : Set}(x : A) : A -> Set where
  24. refl : x == x
  25. compare : (n m : Nat) -> Maybe (n == m)
  26. compare zero zero = just refl
  27. compare (suc _) zero = nothing
  28. compare zero (suc _) = nothing
  29. compare (suc n)(suc m) with compare n m
  30. compare (suc n)(suc .n) | just refl = just refl
  31. compare (suc n)(suc m) | nothing = nothing
  32. -- To add more than one argument separate by |
  33. silly : Nat -> Nat
  34. silly zero = zero
  35. silly (suc n) with n | n
  36. silly (suc n) | zero | suc m = m -- the values of the extra argument are
  37. -- not taken into consideration
  38. silly (suc n) | _ | _ = n
  39. {-
  40. The parity example
  41. -}
  42. -- This is a cute example of what you can do with with.
  43. data Parity : Nat -> Set where
  44. even : (k : Nat) -> Parity (k * 2)
  45. odd : (k : Nat) -> Parity (1 + k * 2)
  46. parity : (n : Nat) -> Parity n
  47. parity zero = even 0
  48. parity (suc n) with parity n
  49. parity (suc .( k * 2)) | even k = odd k
  50. parity (suc .(1 + k * 2)) | odd k = even (suc k)
  51. half : Nat -> Nat
  52. half n with parity n
  53. half .( k * 2) | even k = k
  54. half .(1 + k * 2) | odd k = k
  55. mainS = showNat (half 44)
  56. {-
  57. What's next?
  58. -}
  59. -- Move on to: Modules.agda