Debian Codegraph @

doc/README/Function/Reasoning.agda

raw
1 ------------------------------------------------------------------------
2 -- The Agda standard library
3 --
4 -- Some examples showing how the Function.Reasoning module can be used
5 -- to perform "functional reasoning" similar to what is being described
6 -- in: https://stackoverflow.com/q/22676703/3168666
7 ------------------------------------------------------------------------
8
9 {-# OPTIONS --with-K #-}
10
11 module README.Function.Reasoning where
12
13 -- Function.Reasoning exports a flipped application (_|>_) combinator
14 -- as well as a type annotation (_∶_) combinator.
15
16 open import Function.Reasoning
17
18 ------------------------------------------------------------------------
19 -- A simple example
20
21 module _ {A B C : Set} {A→B : A → B} {B→C : B → C} where
22
23 -- Using the combinators we can, starting from a value, chain various
24 -- functions whilst tracking the types of the intermediate results.
25
26 A→C : A → C
27 A→C a =
28 a ∶ A
29 |> A→B ∶ B
30 |> B→C ∶ C
31
32 ------------------------------------------------------------------------
33 -- A more concrete example
34
35 open import Data.Nat
36 open import Data.List.Base
37 open import Data.Char.Base
38 open import Data.String.Base as String using (String; toList; fromList)
39 open import Data.String.Properties as String using (_==_)
40 open import Function.Base using (_∘_)
41 open import Data.Bool hiding (_≤?_)
42 open import Data.Product.Base using (_×_; <_,_>; uncurry; proj₁)
43 open import Agda.Builtin.Equality
44
45 -- This can give us for instance this decomposition of a function
46 -- collecting all of the substrings of the input which happen to be
47 -- palindromes:
48
49 subpalindromes : String → List String
50 subpalindromes str = let Chars = List Char in
51 str ∶ String
52 -- first generate the substrings
53 |> toList ∶ Chars
54 |> inits ∶ List Chars
55 |> concatMap tails ∶ List Chars
56 -- then only keeps the ones which are not singletons
57 |> filter (λ cs → 2 ≤? length cs) ∶ List Chars
58 -- only keep the ones that are palindromes
59 |> map < fromList , fromList ∘ reverse > ∶ List (String × String)
60 |> filter (uncurry String._≟_) ∶ List (String × String)
61 |> map proj₁ ∶ List String
62
63 -- Test cases
64
65 _ : subpalindromes "doctoresreverse" ≡ "eve" ∷ "rever" ∷ "srevers" ∷ "esreverse" ∷ []
66 _ = refl
67
68 _ : subpalindromes "elle-meme" ≡ "ll" ∷ "elle" ∷ "mem" ∷ "eme" ∷ []
69 _ = refl