I have to write a Haskell program that does the following:
Main> dotProduct [(1,3),(2,5),(3,3)] 2
[(2,3),(4,5),(6,3)]
I have to do it both with and without map function.
I already did it without map, but I have no clue to do it with map.
My dotProduct without map function:
dotProduct :: [(Float, Integer)] -> Float -> [(Float, Integer)]
dotProduct [] _ = []
dotProduct [(x,y)] z = [(x*z,y)]
dotProduct ((x,y):xys) z = (x*z,y):dotProduct (xys) z
So I really need help with the map version.
EEVIAC already posted the answer, so I’ll just explain how to come up with it yourself. As you probably know,
maphas the type signature(a -> b) -> [a] -> [b]. Now,dotProducthas the type[(Float, Integer)] -> Float -> [(Float, Integer)]and you’ll callmapsomewhere in there, so it has to look something like this:where
???is a function of typeFloat -> (Float, Integer) -> (Float, Integer)– this follows immediately from the type signature ofmapand from the fact that we passzto the function, which we have to do, simply because there’s no other place to use it in.The thing with
mapand higher order functions in general is that you have to keep in mind what the higher order function does and “simply” supply it with the correct function. Asmapapplies a given function to all elements in the list, your function only needs to work with one element, and you can forget all about the list –mapwill take care of it.