Exercises part 1
-
Implement a function
len : List a -> Natfor calculating the length of aList. For example,len [1, 1, 1]produces3. -
Implement function
headfor non-empty vectors:head : Vect (S n) a -> aNote, how we can describe non-emptiness by using a pattern in the length of
Vect. This rules out theNilcase, and we can return a value of typea, without having to wrap it in aMaybe! Make sure to add animpossibleclause for theNilcase (although this is not strictly necessary here). -
Using
headas a reference, declare and implement functiontailfor 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
foldSemifor accumulating the values stored in aListthroughSemigroups append operator ((<+>)). (Make sure to only use aSemigroupconstraint, as opposed to aMonoidconstraint.) -
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
aand a functiona -> a, we'd like to generateVects ofas, the first value of which isa, the second value beingf a, the third beingf (f a)and so on.For instance, if
ais 1 andfis(* 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 fromreplicateif you don't know where to start. -
Given an initial value of a state type
sand a functionfun : s -> (s,a), we'd like to generateVects ofas. 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
nFibonacci 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 aVectof the same length. Use holes if you get stuck:fromList : (as : List a) -> Vect (length as) aNote 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.