Using a function passed as an argument to various types in Haskell

Is there a way to apply a function passed as an argument to two different types? As a far-fetched example, I can create (Maybe Int, Maybe Bool)with an expression (Just 3, Just True), but if I try to make this behavior more general using a function

generic :: (a -> Maybe a) -> (Maybe Int, Maybe Bool)
generic f = (f 3, f True)

so that I can do something like generic Just, the compiler complains because the type variable ais constant.

In this case, the general function is applied to the tree structure, where each node is parameterized by a type.

+4
source share
1 answer

This can be achieved using rank 2 polymorphism as follows:

{-# LANGUAGE Rank2Types #-}
generic :: (forall a. a -> Maybe a) -> (Maybe Int, Maybe Bool)
generic f = (f 3, f True)

( , generic, , , ),

genericNum :: (forall a. Num a => a -> a) -> (Int, Integer)
genericNum f = (f 3, f 9)
+9

Source: https://habr.com/ru/post/1627382/


All Articles