3

Is it possible to write a function with signature Monad m => (a -> m a) -> m (a -> a) ?

For example I have a function


func :: Int -> IO Int
func n = pure $ n + 1

Can I transform it into func' :: IO (Int -> Int) ?

duplode
  • 33,731
  • 7
  • 79
  • 150
  • 1
    well imagine that `m ~ []` (`[]` is an instance of `Monad`), then you thus convert an `Int -> [Int]` for example to an `[Int -> Int]`. Not in general no. – Willem Van Onsem May 10 '23 at 08:52
  • 1
    For certain monadic instances that is possible, I unfortunately can not remember instantly the name of this algebraic structure, but not for monads in general. – Willem Van Onsem May 10 '23 at 08:53
  • 2
    For `IO` it also makes no sense, an `IO` action that returns a function is something else than a function that retuns an `IO` action. – Willem Van Onsem May 10 '23 at 08:55
  • 2
    @WillemVanOnsem The structure is `Distributive` (or, equivalently, `Representable`). See also: [*Is there any typeclass that defines the function from a -> m b to m (a -> b)?*](https://stackoverflow.com/q/75928651/2751851) – duplode May 10 '23 at 14:57
  • 1
    "Is it possible to write a function with signature `Monad m => (a -> m a) -> m (a -> a)` ?" If you just care about that type, then `const (pure id)` will do, but I imagine that doesn't work the way you had in mind. – Joseph Sible-Reinstate Monica May 11 '23 at 06:06
  • Also, consider what would happen if you transformed `readFile` the way you had in mind. – Joseph Sible-Reinstate Monica May 11 '23 at 06:08

0 Answers0