Studying the book Haskell Programming from First Principles, I've come across the following exercise in Chapter 6, "Typeclasses":
-- Hint: use some arithmetic operation to
-- combine values of type 'b'. Pick one.
arith :: Num b => (a -> b) -> Integer -> a -> b
arith = ???
I have come up with the following solution, and I call it a 'solution' because it compiles:
arith f _ x = f x
But I'm somewhat confused how to 'interpret' what I've just written above. My 'reading' of the type signature of arith
is something like the following:
arith
takes one function, oneInteger
, a parameter of typea
, and returns a result that is of typeb
; moreover, the function thatarith
takes as the first parameter is a function that takes a parameter of typea
and returns a value of typeb
, and that value has to be of typeb
whose typeclass is (or 'constrained') byNum
.
and after that, I came up with the 'solution' above but I haven't used "some arithmetic operation to combine values of type 'b'". Somehow I think either the 'hint' is misleading, or it is perfectly fine, and I'm missing something, if that's the case, then what am I missing?
I think the intended solution is:
arith f i a = f a + fromInteger i
Or one with +
replaced by -
or *
.
To recap the requirements: In this exercise you have to implement a function that:
Matches type signature arith :: Num b => (a -> b) -> Integer -> a -> b
.
Uses arithmetic operation to combine values of type b
.
You are given three values of types (a -> b)
, Integer
and a
. As a first step you need to convert them to two values of type b
. You can get first one by applying (a -> b)
to a
. Then you are left with value of type Integer
. When you notice that instances of typeclass Num
support function fromInteger :: Integer -> a
(where type a
is type b
in context of function we are defining), it becomes clear that you can obtain second value of type b
by applying fromInteger
to your Integer
value. As a second step you combine two values of type b
using one of arithmetic operations defined in Num
typeclass.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With