How to make Vect n Int an instance of Monoid

In Idris Vect n a, this is a data type representing an n length vector containing elements of type a. Imagine I have a function:

foo : Int -> Vect 4 Int
foo n = [n-1, n, n+1, n*4]

The body of the function is not important, it can be all that the 4 Ints vector returns. Now I want to use this function with concatMap as follows:

bar : Vect n Int -> Vect (4*n) Int
bar vals = concatMap foo vals

A bar is a function that takes an Int vector of length n and returns a length of 4 * n.

Typical concatMap signature:

Prelude.Foldable.concatMap : Foldable t => Monoid m => (a -> m) -> t a -> m

And therefore, if I try to compile a bar, I get an error:

 When elaborating right hand side of bar:
     Can't resolve type class Monoid (Vect (plus n (plus n (plus n (plus n 0)))) Int)

This means that Vect n Int is not an instance of a monoid. To make it an instance of a monoid, I need to implement:

Prelude.Algebra.neutral : Monoid a => a

Unfortunately, however, I am not sure how to do this. The list implements a monoid as follows:

instance Monoid (List a) where
    neutral = []

But if I try to implement a monoid with neutral = [] for Vect n Int, I get an error:

 When elaborating right hand side of Prelude.Algebra.Vect n Int instance of Prelude.Algebra.Monoid, method neutral:
 |   Can't unify
 |           Vect 0 Int
 |   with
 |           Vect n Int
 |   
 |   Specifically:
 |           Can't unify
 |                   0
 |           with
 |                   n

, , Vect?

+4
1

, , concatMap. concatMap:

(Foldable t, Monoid m) => (a -> m) -> t a -> m

, m Monoid (a -> m), . Vect n a. :

concatMap foo vals

foo a -> Vect 4 a, concatMap, , Vect (4*n) a, n - . concatMap, concatMap, :

(Foldable t, Monoid m, Monoid m1) => (a -> m) -> t a -> m1

, , , concatMap .

[a] Vect n a , [] , concatMap. Monoid [] .

, , , , Vect n a . a -> b -> c, Vect Vect n a -> Vect m a -> Vect (n+m) a, : [a] -> [a] ->[a].


, , , , Monoid Vect n a neutral Vect n a, [] Vect 0 a.

Monoid Vect n a. , .

neutral n, , , neutral Monoid. , neutral Vect n a replicate n neutral.

Monoid .

, :

instance Monoid a => Monoid (Vect n a) where
    neutral = replicate n neutral

instance Semigroup a => Semigroup (Vect n a) where
    Nil <+> Nil = Nil
    (x :: xs) <+> (y :: ys) = (x <+> y) :: (xs <+> ys)

, / Idris, , . Haskell, .

+7

All Articles