Exercises part 1
-
Implement a function
len : List a -> Nat
for calculating the length of aList
. For example,len [1, 1, 1]
produces3
. -
Implement function
head
for non-empty vectors:head : Vect (S n) a -> a
Note, how we can describe non-emptiness by using a pattern in the length of
Vect
. This rules out theNil
case, and we can return a value of typea
, without having to wrap it in aMaybe
! Make sure to add animpossible
clause for theNil
case (although this is not strictly necessary here). -
Using
head
as a reference, declare and implement functiontail
for non-empty vectors. The types should reflect that the output is exactly one element shorter than the input. -
Implement
zipWith3
. If possible, try to doing so without looking at the implementation ofzipWith
:zipWith3 : (a -> b -> c -> d) -> Vect n a -> Vect n b -> Vect n c -> Vect n d
-
Declare and implement a function
foldSemi
for accumulating the values stored in aList
throughSemigroup
s append operator ((<+>)
). (Make sure to only use aSemigroup
constraint, as opposed to aMonoid
constraint.) -
Do the same as in Exercise 4, but for non-empty vectors. How does a vector's non-emptiness affect the output type?
-
Given an initial value of type
a
and a functiona -> a
, we'd like to generateVect
s ofa
s, the first value of which isa
, the second value beingf a
, the third beingf (f a)
and so on.For instance, if
a
is 1 andf
is(* 2)
, we'd like to get results similar to the following:[1,2,4,8,16,...]
.Declare and implement function
iterate
, which should encapsulate this behavior. Get some inspiration fromreplicate
if you don't know where to start. -
Given an initial value of a state type
s
and a functionfun : s -> (s,a)
, we'd like to generateVect
s ofa
s. Declare and implement functiongenerate
, which should encapsulate this behavior. Make sure to use the updated state in every new invocation offun
.Here's an example how this can be used to generate the first
n
Fibonacci numbers:generate 10 (\(x,y) => let z = x + y in ((y,z),z)) (0,1) [1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
-
Implement function
fromList
, which converts a list of values to aVect
of the same length. Use holes if you get stuck:fromList : (as : List a) -> Vect (length as) a
Note how, in the type of
fromList
, we can calculate the length of the resulting vector by passing the list argument to function length. -
Consider the following declarations:
maybeSize : Maybe a -> Nat
fromMaybe : (m : Maybe a) -> Vect (maybeSize m) a
Choose a reasonable implementation for maybeSize
and implement fromMaybe
afterwards.