# How to create Arbitrary instance for dependent types?

**URL:** <https://discourse.haskell.org/t/how-to-create-arbitrary-instance-for-dependent-types/6990>\
**Category:** Learn\
**Created:** [July 13, 2023, 9:19am UTC](https://discourse.haskell.org/t/how-to-create-arbitrary-instance-for-dependent-types/6990 "2023-07-13T09:19:42Z")\
**Posts on this page:** 1\
**Showing post:** 23

<div class="post-metadata">

**Author:** ![Bj0rn](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/bj0rn/32/3456_2.png) [@Bj0rn](https://discourse.haskell.org/u/Bj0rn)\
**Post date:** [July 14, 2023, 4:30pm UTC](https://discourse.haskell.org/t/how-to-create-arbitrary-instance-for-dependent-types/6990/23 "2023-07-14T16:30:05Z")

</div>

The linked typechecker plugin should help solve those trivial constraints, like `KnownNat (n + 1)`, given `KnownNat n`. But a plugin is not a necessity.

The `constraints` library comes packed with many useful “proofs” about `Nat` arithmetic in the [`Data.Constraint.Nat`](https://hackage.haskell.org/package/constraints-0.10.1/docs/Data-Constraint-Nat.html) module.

`constraints` defines its own concepts of `Dict`s (a constraint captured as a value) and `:-` (an “entailment” or implication; `a :- b` means that the constraint `a` “entails” the constraint `b`).

Those concepts may seem a bit abstract in the beginning. But let’s look at how we can use the library to solve the `Could not deduce (KnownNat (n + 1))` issue.

Some necessary extensions:

```haskell
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeOperators #-}

```

We need to produce a `forall n. KnownNat n :- KnownNat (n + 1)` value and then we need to “dispatch” it, so to speak, around the problematic expression.

For a first part, `Data.Constraint.Nat` has

```haskell
plusNat :: forall n m. (KnownNat n, KnownNat m) :- KnownNat (n + m)

```

That’s what we need, with `m ~ 1` (GHC finds the `KnownNat 1` instance automatically).

The problematic expression from earlier was `SomeVect` on the rhs of

```haskell
someVectCons x (SomeVect xs) = SomeVect $ VCons x xs

```

`constraints` has the `\\` operator for “dispatching” an entailment. It’s used like this:

```haskell
someVectCons x (SomeVect @n xs) = (SomeVect \\ plusNat @n @1) $ VCons x xs

```

And now it compiles!

---

_[View the full topic](https://discourse.haskell.org/t/how-to-create-arbitrary-instance-for-dependent-types/6990)._
