πŸ“₯ Download raw
module Padova2025.ProgrammingBasics.Vectors where

Vectors

open import Padova2025.ProgrammingBasics.Naturals.Base
open import Padova2025.ProgrammingBasics.Naturals.Arithmetic
infixr 5 _∷_
data Vector (A : Set) : β„• β†’ Set where
  []  : Vector A zero
  _∷_ : {n : β„•} β†’ A β†’ Vector A n β†’ Vector A (succ n)

Exercise: Length

Define a function which computes the length of a given vector. There are two possible implementations, one which runs in constant time and one which runs in linear time.

lengthV : {n : β„•} {A : Set} β†’ Vector A n β†’ β„•
lengthV = {!!}

Exercise: Replication

Define a function replicateV which reads a number n and an element x as input and outputs a vector containing n copies of x.

replicateV : {A : Set} β†’ (n : β„•) β†’ A β†’ Vector A n
replicateV = {!!}

Exercise: Map

Define the map function for vectors. For instance, map f (x ∷ y ∷ z ∷ []) should reduce to f x ∷ f y ∷ f z ∷ [].

mapV : {n : β„•} {A B : Set} β†’ (A β†’ B) β†’ Vector A n β†’ Vector B n
mapV = {!!}

Exercise: zipWith

For instance, β€œzipWithV f (x ∷ y ∷ []) (a ∷ b ∷ [])” should evaluate to β€œf x a ∷ f y b ∷ []”.

zipWithV : {A B C : Set} {n : β„•} β†’ (A β†’ B β†’ C) β†’ Vector A n β†’ Vector B n β†’ Vector C n
zipWithV = {!!}

Exercise: drop

For instance, dropV one (a ∷ b ∷ c ∷ []) should evaluate to b ∷ c ∷ [].

dropV : {A : Set} {n : β„•} (k : β„•) β†’ Vector A (k + n) β†’ Vector A n
dropV = {!!}

Exercise: take

For instance, takeV one (a ∷ b ∷ c ∷ []) should evaluate to a ∷ [].

takeV : {A : Set} {n : β„•} (k : β„•) β†’ Vector A (k + n) β†’ Vector A k
takeV = {!!}

Exercise: Concatenation

For instance, (a ∷ b ∷ []) ++V (c ∷ d ∷ []) should evaluate to a ∷ b ∷ c ∷ d ∷ [].

_++V_ : {A : Set} {n m : β„•} β†’ Vector A n β†’ Vector A m β†’ Vector A (n + m)
_++V_ = {!!}

Exercise: Snocking

Write a function which appends a new element at the end. For instance, snocV (a ∷ b ∷ []) c should evaluate to a ∷ b ∷ c ∷ [].

snocV : {A : Set} {n : β„•} β†’ Vector A n β†’ A β†’ Vector A (succ n)
snocV = {!!}

Exercise: Reversal

For instance, reverseV (a ∷ b ∷ c ∷ []) should evaluate to c ∷ b ∷ a ∷ [].

reverseV : {A : Set} {n : β„•} β†’ Vector A n β†’ Vector A n
reverseV = {!!}

Exercise: Flattening vectors of vectors

For instance, concatV ((a ∷ b ∷ []) ∷ (c ∷ d ∷ []) ∷ []) should evaluate to a ∷ b ∷ c ∷ d ∷ [].

concatV : {!!}
concatV = {!!}

Note that this exercise nontrivially depends on the somewhat arbitrary choices in implementing addition and multiplication of natural numbers: Should the case split be on the first or on the second argument? Should succ a Β· b be defined as b + a Β· b or as a Β· b + b? Et cetera. This state of affairs is unsatisfying and there are a couple of proposals attacking this problem. One of these is objective type theory by Benno van den Bergh and Martijn den Besten.