Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to interpret this Haskell code that type checks?

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, one Integer, a parameter of type a, and returns a result that is of type b; moreover, the function that arith takes as the first parameter is a function that takes a parameter of type a and returns a value of type b, and that value has to be of type b whose typeclass is (or 'constrained') by Num.

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?

like image 248
Emre Sevinç Avatar asked Mar 12 '23 07:03

Emre Sevinç


1 Answers

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:

  1. Matches type signature arith :: Num b => (a -> b) -> Integer -> a -> b.

  2. 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.

like image 53
TeWu Avatar answered Mar 19 '23 08:03

TeWu