6

What is the proper way to use the "ap" monad in Haskell? I want to do something similar to this:

main = (putStr . ap (++) show) "main = (putStr . ap (++) show) "

but I get the error "Not in scope: 'ap'."

Using "import Control.Monad" does nothing. And I have tried giving it

"ap :: Monad m => m (a -> b) -> m a -> m b" 

then I get "The type signature for `ap' lacks an accompanying binding"

GossJ
  • 69
  • 8

1 Answers1

10

Importing Control.Monad should give you ap. However, in all but the most recent versions of GHC (7.6.1 and newer), you'll also need to import Control.Monad.Instances to use the monad instance for functions.

Alternatively, you can import Control.Applicative which gives you the <*> operator, which is ap generalized to Applicative, as well as the necessary instances to use it with functions.

hammar
  • 138,522
  • 17
  • 304
  • 385
  • 2
    And alternatively, if we want to avoid imports, instead of importing either module we can just use `(\f g x -> f x (g x))` (the S combinator, which `(<*>)` and `ap` are type class-generic versions thereof). – Luis Casillas Apr 29 '13 at 17:26
  • @sacundim: Who would redefine a standard library function just to "avoid imports"? I mean, you will need imports anyway for any non-trivial programs – Niklas B. Apr 29 '13 at 21:02
  • 2
    @NiklasB.: possibly somebody trying to write a Quine program, like GossJ is trying to do. I did not work out how the original program would need to be modified to incorporate the import, because inlining the S combinator just works right away. – Luis Casillas Apr 30 '13 at 01:27
  • @sacundim: Should have paid more attention to the question, sorry for my useless comment :) – Niklas B. May 01 '13 at 23:24