A set of challenges for jump starting your understanding of monads.
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
Write a function that calculates the product of the tail of a list. Use your tailMay
function and the product
function defined in the Prelude. This function should return Nothing
when passed an empty list, Just 1
when passed a list of one element (which is what the Prelude’s product
function does), and return the product of the tail for larger lists.
tailProd :: Num a => [a] -> Maybe a
Now write a similar but slightly different function:
tailSum :: Num a => [a] -> Maybe a
These two functions have a lot in common. See if you can abstract out the commonality. To do this, write another function called transMaybe
that is the generalized version of both of these. Spend some time working on this before you look at the next hex encoded hint:
7472616E734D61796265203A3A202861202D3E206229202D3E204D617962652061202D3E204D617962652062
Write a function with that type signature and then go back and implement tailProd
and tailSum
in terms of that function.
Now that you have that finished, use transMaybe
again, with maximumMay
and minimumMay
, to write two more functions tailMax
and tailMin
. These functions will have different type signatures than tailProd
and tailSum
. See if you can figure out what they should be. If you can’t figure it out, here’s a hex encoded hint.
7461696C4D6178203A3A204F72642061203D3E205B615D202D3E204D6179626520284D61796265206129
That type signature is different from the ones above for tailProd
and tailSum
and less convenient to use. To collapse the two levels you’ll need another helper function. See if you can figure out what the type signature of this function should be and how to implement it. Call this function combine
. Here is its hex encoded type signature if you need help.
636F6D62696E65203A3A204D6179626520284D61796265206129202D3E204D617962652061