Bits.agda 981 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. {-# OPTIONS --no-termination-check #-}
  2. module Data.Bits where
  3. import Prelude
  4. import Logic.Base
  5. import Data.List as List
  6. import Data.Nat as Nat
  7. import Data.Bool as Bool
  8. open Prelude
  9. open Nat
  10. open Bool
  11. open List
  12. Bit = Bool
  13. shiftL : Nat -> Nat -> Nat
  14. shiftL n i = n * 2 ^ i
  15. sucBits : List Bit -> List Bit
  16. sucBits [] = true :: []
  17. sucBits (false :: xs) = true :: xs
  18. sucBits (true :: xs) = false :: sucBits xs
  19. -- Least significant bit first. Last bit (when present) is always one.
  20. toBits : Nat -> List Bit
  21. toBits zero = []
  22. toBits (suc n) = sucBits (odd n :: toBits (div n 2))
  23. fromBits : List Bit -> Nat
  24. fromBits xs = foldr (\b n -> bitValue b + 2 * n) 0 xs
  25. where
  26. bitValue : Bit -> Nat
  27. bitValue b = if b then 1 else 0
  28. nofBits : Nat -> Nat
  29. nofBits = length ∘ toBits
  30. module Proofs where
  31. open Logic.Base
  32. -- fromBits∘toBits=id : (n : Nat) -> fromBits (toBits n) ≡ n
  33. -- fromBits∘toBits=id zero = tt
  34. -- fromBits∘toBits=id (suc n) = ?