instance-arguments.lagda.rst 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. ..
  2. ::
  3. {-# OPTIONS --rewriting --sized-types #-}
  4. module language.instance-arguments where
  5. open import language.built-ins
  6. using (Bool; true; false; List; _∷_; []; Nat; _-_; zero; suc; _+_)
  7. renaming (_==_ to natEquals)
  8. open import Agda.Primitive
  9. postulate undefined : ∀ {u} {A : Set u} → A
  10. .. _instance-arguments:
  11. ******************
  12. Instance Arguments
  13. ******************
  14. .. contents::
  15. :depth: 2
  16. :local:
  17. Instance arguments are a special kind of :ref:`implicit arguments
  18. <implicit-arguments>` that get solved by a special :ref:`instance
  19. resolution <instance-resolution>` algorithm, rather than by the
  20. unification algorithm used for normal implicit arguments.
  21. Instance arguments are the Agda equivalent of Haskell type class
  22. constraints and can be used for many of the same purposes.
  23. An instance argument will be resolved if its type is a *named type*
  24. (i.e. a data type or record type) or a *variable type* (i.e. a
  25. previously bound variable of type `Set ℓ`), and a unique *instance* of
  26. the required type can be built from :ref:`declared
  27. instances <declaring-instances>` and the current context.
  28. Usage
  29. -----
  30. Instance arguments are enclosed in double curly braces ``{{ }}``, e.g. ``{{x : T}}``.
  31. Alternatively they can be enclosed, with proper spacing, e.g. ``⦃ x : T ⦄``, in the
  32. unicode braces ``⦃ ⦄`` (``U+2983`` and ``U+2984``, which can be typed as
  33. ``\{{`` and ``\}}`` in the :ref:`Emacs mode <unicode-input>`).
  34. For instance, given a function ``_==_``
  35. ..
  36. ::
  37. _||_ : Bool → Bool → Bool
  38. true || _ = true
  39. false || y = y
  40. _&&_ : Bool → Bool → Bool
  41. false && _ = false
  42. true && y = y
  43. infixl 10 _||_ _&&_
  44. _++_ : ∀ {u} {A : Set u} → List A → List A → List A
  45. [] ++ xs = xs
  46. (x ∷ xs) ++ ys = x ∷ (xs ++ ys)
  47. module eq-prototype (Eq : Set → Set) where
  48. ::
  49. _==_ : {A : Set} {{eqA : Eq A}} → A → A → Bool
  50. ..
  51. ::
  52. _==_ = undefined
  53. for some suitable type ``Eq``, you might define
  54. ..
  55. ::
  56. module elem-one where
  57. ::
  58. elem : {A : Set} {{eqA : Eq A}} → A → List A → Bool
  59. elem x (y ∷ xs) = x == y || elem x xs
  60. elem x [] = false
  61. Here the instance argument to ``_==_`` is solved by the corresponding argument
  62. to ``elem``. Just like ordinary implicit arguments, instance arguments can be
  63. given explicitly. The above definition is equivalent to
  64. ..
  65. ::
  66. module elem-bis where
  67. ::
  68. elem : {A : Set} {{eqA : Eq A}} → A → List A → Bool
  69. elem {{eqA}} x (y ∷ xs) = _==_ {{eqA}} x y || elem {{eqA}} x xs
  70. elem x [] = false
  71. A very useful function that exploits this is the function ``it`` which lets you
  72. apply instance resolution to solve an arbitrary goal::
  73. it : ∀ {a} {A : Set a} → {{A}} → A
  74. it {{x}} = x
  75. As the last example shows, the name of the instance argument can be
  76. omitted in the type signature:
  77. ..
  78. ::
  79. module example-underscore (Eq : Set → Set) where
  80. ::
  81. _==_ : {A : Set} → {{Eq A}} → A → A → Bool
  82. ..
  83. ::
  84. _==_ = undefined
  85. Defining type classes
  86. ~~~~~~~~~~~~~~~~~~~~~
  87. The type of an instance argument should have the form ``{Γ} → C vs``,
  88. where ``C`` is a postulated name, a bound variable, or the name of a
  89. data or record type, and ``{Γ}`` denotes an arbitrary number of
  90. implicit or instance arguments (see :ref:`dependent-instances` below
  91. for an example where ``{Γ}`` is non-empty).
  92. Instances with explicit arguments are also accepted but will not be
  93. considered as instances because the value of the explicit arguments
  94. cannot be derived automatically. Having such an instance has no effect
  95. and thus raises a warning.
  96. Instance arguments whose types end in any other type are currently
  97. also accepted but cannot be resolved by instance search, so they must
  98. be given by hand. For this reason it is not recommended to use such
  99. instance arguments. Doing so will also raise a warning.
  100. Other than that there are no requirements on the type of an instance
  101. argument. In particular, there is no special declaration to say that a
  102. type is a "type class". Instead, Haskell-style type classes are
  103. usually defined as :ref:`record types <record-types>`. For instance,
  104. ::
  105. record Monoid {a} (A : Set a) : Set a where
  106. field
  107. mempty : A
  108. _<>_ : A → A → A
  109. In order to make the fields of the record available as functions taking
  110. instance arguments you can use the special module application
  111. ..
  112. ::
  113. module monoid-record-open where
  114. ::
  115. open Monoid {{...}} public
  116. This will bring into scope
  117. ..
  118. ::
  119. module open-prototypes where
  120. ::
  121. mempty : ∀ {a} {A : Set a} → {{Monoid A}} → A
  122. _<>_ : ∀ {a} {A : Set a} → {{Monoid A}} → A → A → A
  123. ..
  124. ::
  125. mempty = undefined
  126. _<>_ = undefined
  127. Superclass dependencies can be implemented using :ref:`instance-fields`.
  128. See :ref:`module-application` and :ref:`record-modules` for details about how
  129. the module application is desugared. If defined by hand, ``mempty`` would be
  130. ..
  131. ::
  132. module mempty-by-hand where
  133. ::
  134. mempty : ∀ {a} {A : Set a} → {{Monoid A}} → A
  135. mempty {{mon}} = Monoid.mempty mon
  136. Although record types are a natural fit for Haskell-style type
  137. classes, you can use instance arguments with data types to good
  138. effect. See the :ref:`instance-arguments-examples` below.
  139. .. _declaring-instances:
  140. Declaring instances
  141. ~~~~~~~~~~~~~~~~~~~
  142. As seen above, instance arguments in the context are available when solving
  143. instance arguments, but you also need to be able to
  144. define top-level instances for concrete types. This is done using the
  145. ``instance`` keyword, which starts a :ref:`block <lexical-structure-layout>` in
  146. which each definition is marked as an instance available for instance
  147. resolution. For example, an instance ``Monoid (List A)`` can be defined as
  148. ..
  149. ::
  150. module list-monoid where
  151. ::
  152. instance
  153. ListMonoid : ∀ {a} {A : Set a} → Monoid (List A)
  154. ListMonoid = record { mempty = []; _<>_ = _++_ }
  155. Or equivalently, using :ref:`copatterns <copatterns>`:
  156. ..
  157. ::
  158. open Monoid {{...}} public
  159. ::
  160. instance
  161. ListMonoid : ∀ {a} {A : Set a} → Monoid (List A)
  162. mempty {{ListMonoid}} = []
  163. _<>_ {{ListMonoid}} xs ys = xs ++ ys
  164. Top-level instances must target a named type (``Monoid`` in this case), and
  165. cannot be declared for types in the context.
  166. You can define local instances in let-expressions in the same way as a
  167. top-level instance. For example::
  168. mconcat : ∀ {a} {A : Set a} → {{Monoid A}} → List A → A
  169. mconcat [] = mempty
  170. mconcat (x ∷ xs) = x <> mconcat xs
  171. sum : List Nat → Nat
  172. sum xs =
  173. let instance
  174. NatMonoid : Monoid Nat
  175. NatMonoid = record { mempty = 0; _<>_ = _+_ }
  176. in mconcat xs
  177. Instances can have instance arguments themselves, which will be filled in
  178. recursively during instance resolution. For instance,
  179. ..
  180. ::
  181. module eq-list where
  182. ::
  183. record Eq {a} (A : Set a) : Set a where
  184. field
  185. _==_ : A → A → Bool
  186. open Eq {{...}} public
  187. instance
  188. eqList : ∀ {a} {A : Set a} → {{Eq A}} → Eq (List A)
  189. _==_ {{eqList}} [] [] = true
  190. _==_ {{eqList}} (x ∷ xs) (y ∷ ys) = x == y && xs == ys
  191. _==_ {{eqList}} _ _ = false
  192. eqNat : Eq Nat
  193. _==_ {{eqNat}} = natEquals
  194. ex : Bool
  195. ex = (1 ∷ 2 ∷ 3 ∷ []) == (1 ∷ 2 ∷ []) -- false
  196. Note the two calls to ``_==_`` in the right-hand side of the second clause. The
  197. first uses the ``Eq A`` instance and the second uses a recursive call to
  198. ``eqList``. In the example ``ex``, instance resolution, needing a value of type ``Eq
  199. (List Nat)``, will try to use the ``eqList`` instance and find that it needs an
  200. instance argument of type ``Eq Nat``, it will then solve that with ``eqNat``
  201. and return the solution ``eqList {{eqNat}}``.
  202. .. note::
  203. At the moment there is no termination check on instances, so it is possible
  204. to construct non-sensical instances like
  205. ``loop : ∀ {a} {A : Set a} → {{Eq A}} → Eq A``.
  206. To prevent looping in cases like this, the search depth of instance search
  207. is limited, and once the maximum depth is reached, a type error will be
  208. thrown. You can set the maximum depth using the ``--instance-search-depth``
  209. flag.
  210. Restricting instance search
  211. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  212. To restrict an instance to the current module, you can mark it as
  213. `private`. For instance,
  214. ..
  215. ::
  216. module private-instance where
  217. open import Agda.Builtin.Equality
  218. ::
  219. record Default (A : Set) : Set where
  220. field default : A
  221. open Default {{...}} public
  222. module M where
  223. private
  224. instance
  225. defaultNat : Default Nat
  226. defaultNat .default = 6
  227. test₁ : Nat
  228. test₁ = default
  229. _ : test₁ ≡ 6
  230. _ = refl
  231. open M
  232. instance
  233. defaultNat : Default Nat
  234. defaultNat .default = 42
  235. test₂ : Nat
  236. test₂ = default
  237. _ : test₂ ≡ 42
  238. _ = refl
  239. ..
  240. Constructor instances
  241. +++++++++++++++++++++
  242. Although instance arguments are most commonly used for record types,
  243. mimicking Haskell-style type classes, they can also be used with data
  244. types. In this case you often want the constructors to be instances,
  245. which is achieved by declaring them inside an ``instance``
  246. block. Constructors can only be declared as instances if all their
  247. arguments are implicit or instance arguments. See
  248. :ref:`instance-resolution` below for the details.
  249. A simple example of a constructor that can be made an instance is the
  250. reflexivity constructor of the equality type::
  251. data _≡_ {a} {A : Set a} (x : A) : A → Set a where
  252. instance refl : x ≡ x
  253. ..
  254. ::
  255. infix 4 _≡_
  256. This allows trivial equality proofs to be inferred by instance resolution,
  257. which can make working with functions that have preconditions less of a burden.
  258. As an example, here is how one could use this to define a function that takes a
  259. natural number and gives back a ``Fin n`` (the type of naturals smaller than
  260. ``n``)::
  261. data Fin : Nat → Set where
  262. zero : ∀ {n} → Fin (suc n)
  263. suc : ∀ {n} → Fin n → Fin (suc n)
  264. mkFin : ∀ {n} (m : Nat) → {{suc m - n ≡ 0}} → Fin n
  265. mkFin {zero} m {{}}
  266. mkFin {suc n} zero = zero
  267. mkFin {suc n} (suc m) = suc (mkFin m)
  268. five : Fin 6
  269. five = mkFin 5 -- OK
  270. .. code-block: agda
  271. badfive : Fin 5
  272. badfive = mkFin 5 -- Error: No instance of type 1 ≡ 0 was found in scope.
  273. In the first clause of ``mkFin`` we use an :ref:`absurd pattern
  274. <absurd-patterns>` to discharge the impossible assumption ``suc m ≡
  275. 0``. See the :ref:`next section <instance-arguments-examples>` for
  276. another example of constructor instances.
  277. Record fields can also be declared instances, with the effect that the
  278. corresponding projection function is considered a top-level instance.
  279. .. _overlapping-instances:
  280. Overlapping instances
  281. +++++++++++++++++++++
  282. By default, Agda does not allow overlapping instances. Two instances
  283. are defined to overlap if they could both solve the instance goal
  284. when given appropriate solutions for their recursive (instance)
  285. arguments.
  286. For example, in code below, the instances `zero` and `suc` overlap for
  287. the goal `ex₁`, because either one of them can be used to solve the
  288. goal when given appropriate arguments, hence instance search fails.
  289. .. code-block:: agda
  290. infix 4 _∈_
  291. data _∈_ {A : Set} (x : A) : List A → Set where
  292. instance
  293. zero : ∀ {xs} → x ∈ x ∷ xs
  294. suc : ∀ {y xs} → {{x ∈ xs}} → x ∈ y ∷ xs
  295. ex₁ : 1 ∈ 1 ∷ 2 ∷ 3 ∷ 4 ∷ []
  296. ex₁ = it -- overlapping instances
  297. Overlapping instances can be enabled via the ``--overlapping-instances``
  298. flag. Be aware that enabling this flag might lead to an exponential
  299. slowdown in instance resolution and possibly (apparent) looping
  300. behaviour.
  301. .. _instance-arguments-examples:
  302. Examples
  303. ~~~~~~~~
  304. .. _dependent-instances:
  305. Dependent instances
  306. +++++++++++++++++++
  307. ..
  308. ::
  309. data Maybe {a} (A : Set a) : Set a where
  310. nothing : Maybe A
  311. just : A → Maybe A
  312. module dependent-instances where
  313. open Agda.Primitive
  314. Consider a variant on the ``Eq`` class where the equality function produces a
  315. proof in the case the arguments are equal::
  316. record Eq {a} (A : Set a) : Set a where
  317. field
  318. _==_ : (x y : A) → Maybe (x ≡ y)
  319. open Eq {{...}} public
  320. A simple boolean-valued equality function is problematic for types with
  321. dependencies, like the Σ-type
  322. ::
  323. data Σ {a b} (A : Set a) (B : A → Set b) : Set (a ⊔ b) where
  324. _,_ : (x : A) → B x → Σ A B
  325. since given two pairs ``x , y`` and ``x₁ , y₁``, the types of the second
  326. components ``y`` and ``y₁`` can be completely different and not admit an
  327. equality test. Only when ``x`` and ``x₁`` are *really equal* can we hope to
  328. compare ``y`` and ``y₁``. Having the equality function return a proof means
  329. that we are guaranteed that when ``x`` and ``x₁`` compare equal, they really
  330. are equal, and comparing ``y`` and ``y₁`` makes sense.
  331. An ``Eq`` instance for ``Σ`` can be defined as follows::
  332. instance
  333. eqΣ : ∀ {a b} {A : Set a} {B : A → Set b} → {{Eq A}} → {{∀ {x} → Eq (B x)}} → Eq (Σ A B)
  334. _==_ {{eqΣ}} (x , y) (x₁ , y₁) with x == x₁
  335. _==_ {{eqΣ}} (x , y) (x₁ , y₁) | nothing = nothing
  336. _==_ {{eqΣ}} (x , y) (.x , y₁) | just refl with y == y₁
  337. _==_ {{eqΣ}} (x , y) (.x , y₁) | just refl | nothing = nothing
  338. _==_ {{eqΣ}} (x , y) (.x , .y) | just refl | just refl = just refl
  339. Note that the instance argument for ``B`` states that there should be
  340. an ``Eq`` instance for ``B x``, for any ``x : A``. The argument ``x``
  341. must be implicit, indicating that it needs to be inferred by
  342. unification whenever the ``B`` instance is used. See
  343. :ref:`instance-resolution` below for more details.
  344. .. _instance-resolution:
  345. Instance resolution
  346. -------------------
  347. Given a goal that should be solved using instance resolution we proceed in the
  348. following four stages:
  349. Verify the goal
  350. First we check that the goal type has the right shape to be solved
  351. by instance resolution. It should be of the form ``{Γ} → C vs``, where
  352. the target type ``C`` is a variable from the context or the name of
  353. a data or record type, and ``{Γ}`` denotes a telescope of implicit or
  354. instance arguments. If this is not the case instance resolution
  355. fails with an error message\ [#issue1322]_.
  356. Find candidates
  357. In the second stage we compute a set of
  358. *candidates*. :ref:`Let-bound <let-and-where>` variables and
  359. top-level definitions in scope are candidates if they are defined in
  360. an ``instance`` block. Lambda-bound variables, i.e. variables bound
  361. in lambdas, function types, left-hand sides, or module parameters,
  362. are candidates if they are bound as instance arguments using ``{{
  363. }}``. Only candidates of type ``{Δ} → C us``, where ``C`` is the
  364. target type computed in the previous stage and ``{Δ}`` only contains
  365. implicit or instance arguments, are considered.
  366. Check the candidates
  367. We attempt to use each candidate in turn to build an instance of the
  368. goal type ``{Γ} → C vs``. First we extend the current context by
  369. ``{Γ}``. Then, given a candidate ``c : {Δ} → A`` we generate fresh
  370. metavariables ``αs : {Δ}`` for the arguments of ``c``, with ordinary
  371. metavariables for implicit arguments, and instance metavariables,
  372. solved by a recursive call to instance resolution, for instance
  373. arguments.
  374. Next we :ref:`unify <unification>` ``A[Δ := αs]`` with ``C vs`` and apply
  375. instance resolution to the instance metavariables in ``αs``. Both unification
  376. and instance resolution have three possible outcomes: *yes*, *no*, or
  377. *maybe*. In case we get a *no* answer from any of them, the current candidate
  378. is discarded, otherwise we return the potential solution ``λ {Γ} → c αs``.
  379. Compute the result
  380. From the previous stage we get a list of potential solutions. If the list is
  381. empty we fail with an error saying that no instance for ``C vs`` could be
  382. found (*no*). If there is a single solution we use it to solve the goal
  383. (*yes*), and if there are multiple solutions we check if they are all equal.
  384. If they are, we solve the goal with one of them (*yes*), but if they are not,
  385. we postpone instance resolution (*maybe*), hoping that some of the *maybes*
  386. will turn into *nos* once we know more about the involved metavariables.
  387. If there are left-over instance problems at the end of type checking, the
  388. corresponding metavariables are printed in the Emacs status buffer together
  389. with their types and source location. The candidates that gave rise to
  390. potential solutions can be printed with the :ref:`show constraints command
  391. <emacs-global-commands>` (``C-c C-=``).
  392. .. [#issue1322] Instance goal verification is buggy at the moment. See `issue
  393. #1322 <https://github.com/agda/agda/issues/1322>`_.