Reputation: 4475
Type:
data Command a = Command String (a -> IO a)
Functions:
iofunc :: String -> (a -> IO a) -> Command a
iofunc = Command
func :: String -> (a -> a) -> Command a
func s f = iofunc s (return . f)
Can someone explain how (return . f)
type checks with (a -> IO a)
?
Upvotes: 1
Views: 101
Reputation: 6696
I don't know what you mean by "pattern matches" but in this case, return :: a -> IO a
. notice that f :: a -> a
so by threading the result of that on to return
(or composing return
with f
, if you like) we go from a -> a
to a -> IO a
Upvotes: 2
Reputation: 370415
There is no pattern matching going on in your code, so I assume you meant "type checks".
return . f
is a function that takes an argument x
and evaluates to return (f x)
. return
has the type Monad m => a -> m a
and f
has the type a -> a
. Therefore we know that the type of f x
is the same as the type of x
and return (f x)
then has the type m a
where a
is the type of x
and m
is a monad. In other words the type of return . f
is Monad m => a -> m a
, just like the type of return
by itself.
The type required for the second argument to iofunc
is a -> IO a
. Since IO
is a monad, that fits the type Monad m => a -> m a
and thus return . f
has the proper type to be passed as the second argument to iofunc
. Therefore the code type checks.
Upvotes: 6