Is a state monad with two state variable types (in and out) still a monad? - monads

Haskell's state monad State s a forces me to keep the same type of s during the whole do block. But since the state monad is really just a function, what if I define it as State i o a = State (i -> (o, a))?. The return and bind functions would look exactly the same as in the standard state monad, but with the types changed:
return :: a -> State st st a
bind :: (State i o a) -> (a -> (State o o' b)) -> (State i o' b)
I don't think is possible to implement Monad in Haskell using this definition because it expects a single State i o type in bind (only a can change). But this question is not about Haskell but about whether this would technically be a monad or not. Or if not, would it be some kind of superset of a monad (such that all the monad laws still apply but has some extra features)?
This is something I found would be useful in another language I'm working on, which is based on lambda calculus, so I'm using Haskell as a reference. I just don't want this to break other stuff later on where I'd expect the monad laws to apply.

What you are looking for is an indexed Monad. See e.g. the definition in category-extras:
The definition of an indexed Monad:
class IxApplicative m => IxMonad m where
ibind :: (a -> m j k b) -> m i j a -> m i k b
The State indexed Monad:
class IxMonad m => IxMonadState m where
iget :: m i i i
iput :: j -> m i j ()

Related

Monads and SML modules

signature MAPPABLE = sig
type 'a mappable
val fmap : ('a -> 'b) -> 'a mappable -> 'b mappable
end
structure Option : MAPPABLE = struct
type 'a mappable = 'a option
fun fmap f v =
case v of
(SOME x) => SOME (f x)
| NONE => NONE;
end
structure List : MAPPABLE = struct
type 'a mappable = 'a list
fun fmap f v = map f v
end
fun incByFive x = x + 5
Really just to have a function that does stuff with fmap
fun mapToPair f x =
let val b = List.fmap f x
in (b,b)
end
val lst = mapToPair incByFive [1,2,3];
Suppose you want to make a generic implementation, that works for
all instances of MAPPABLE. The following does not work
fun mapToPair f x =
let val b = MAPPABLE.fmap f x
in (b,b)
end
It seems, that SML people point to Functors, if that needs to be done.
I tried implementing one, for a generic implementation of mapToPair
functor FMAPFUNCTOR (structure Q : MAPPABLE)
= struct
fun mapToPair f x =
let val b = Q.fmap f x
in (b,b)
end
end;
However, to use it with what in Haskell I'd call a functor
instance, I need to instantiate the functor (this reminds me of C++
templates for some reason)
structure MAPPABLE_TO_PAIR = FMAPFUNCTOR (structure Q = List);
val lstByPoly = MAPPABLE_TO_PAIR.mapToPair incByFive [1,2,3]
I would have to repeat that instantiation for every MAPPABLE
instance I want to use. I guess Haskell performs something like this,
too. Just implicitly.
Now I wonder if there is any shortcut / sugar for a better "user
experience" in SML that I have missed. Because really, it seems kind
of a lot of boilerplate in the way in order to use this in a code
base.
I guess Haskell performs something like this, too. Just implicitly.
The Haskell standard library defines and imports a ton of type class instances. Given a sufficient set of ML functors, their applications and their implicit compile-time imports, you could achieve something quite convenient.
But Haskell does let you automate type class instance declarations in ways that SML doesn't.
For example, instance Foo t => Bar t where ... is comparable to SML's higher-order functors, but in SML you explicitly have to generate a module that corresponds to Bar t for each concrete Foo t. Haskell also lets you derive instances syntactically.
OCaml had modular implicits from 2014 (example), but they mainly give you syntax sugar to refer to defined functor instances, rather than generate them.
I suspect that the reason ML module systems are still more explicit than Haskell's is because of things like overlapping instances.
Andreas Rossberg contributed 1ML in 2014 in which modules are first-class citizens. That means a function could take a module as an argument, e.g. like this:
;; Higher-kinded polymorphism
type MONAD (m : type => type) =
{
return 'a : a -> m a;
bind 'a 'b : m a -> (a -> m b) -> m b;
};
map 'a 'b (m : type => type) (M : MONAD m) (f : a -> b) mx =
M.bind mx (fun x => M.return (f x));
do map :
'a => 'b => (m : type => type) => (M : MONAD m) => (a -> b) -> m a -> m b;
This is still research-y in the sense that the compiler has "TOY" in its name, but it'd be an example of an ML (although not Standard ML) that does something comparably generic with modules.

haskell: calling a function with different types of lists

I have a function:
sum f l1 l2 = (f l1) + (f l2)
How to correct this function to be working when called with different types of lists? eg:
sum length [1,2] ['a','b']
May as well flesh out my comment in an answer. The usual signature one may be tempted to give is
sum :: Num b => ([a] -> b) -> [a] -> [a] -> b
sum f l1 l2 = f l1 + f l2
The problem here is that the two lists must have the same type, which must be the input type of the function. The solution is to tell GHC that the function actually has the more general type forall a. [a] -> b, which means that we can pick multiple possibly different a instantiations and they all produce the same b.
{-# LANGUAGE RankNTypes #-}
sum' :: Num b => (forall a. [a] -> b) -> [c] -> [d] -> b
sum' f l1 l2 = f l1 + f l2
main = print $ sum' length [1,2] ['a','b']
There's no general way to do this at the moment unfortunately. You could try like this previous answer suggested as follows:
sum' :: Num b => (forall a. [a] -> b) -> [c] -> [d] -> b
sum' f l1 l2 = f l1 + f l2
And whilst this works with length, it doesn't really work with much else.
The issue is that the type signature in this answer Num b => forall a. [a] -> b. That means your function must work for all types of lists, and the only sensible function from Num b => forall a. [a] -> b is length. If you think there's another feel free to give me an example, but I suspect all the other examples are either variations of length or silly ones that return a constant.
And if length is the only sensible argument for sum', then it's silly to define sum', you might as well define sumLength like follows
sumLength :: Num b => [c] -> [d] -> b
sumLength l1 l2 = genericLength l1 + genericLength l2
Indeed, lets define the following:
g :: Enum a => [a] -> Int
g = (foldl' 0 (+)) . (map fromEnum)
This is a weird probably useless function, but it does something non-trivial. It converts all the values to their Enum int representation and sums them and spits out an Integer.
So sum' g l1 l2 should work, but it doesn't. To get this to work, you'd have to define a new function:
sum'' :: Enum c, Enum d => (Enum a => forall a. [a]) -> [c] -> [d] -> Int
sum'' f l1 l2 = f l1 + f l2
And indeed, too use any function with different constraints, you'll have to define a new version of sum.
So really, no, there's no way to answer your question similarly.
I recognised this problem and created the package polydata, which you can check out on hackage (needs some clearer documentation I admit).
It does allow you to make functions which accept polymorphic functions that you can apply to different types, like so:
g :: (c (a -> a'), c (b -> b')) => Poly c -> (a, b) -> (a' -> b')
g f (x,y) = (getPoly f x, getPoly f y)
Which is very similar to your example.
c in the above is a constraint, and looking at the type of g should help you understand what's happening.
Unfortunately, you can't just pass an ordinary function to g, you have to pass one wrapped in a Poly, which is non trivial as you don't get type inference for the Poly constraint (any ideas on how to make this nicer appreciated).
But if you've just got one or a few functions that need this polymorphic behaviour, I wouldn't bother with Poly. But for example, you're finding this issue coming up a lot (I found it came up a lot in unit testing, which is what inspired the creation of my package), then you might find polydata useful.
There's also heterolist, which I created as an extension to polydata allows you to create lists of mixed types and say, map over them in a type safe way. You might find that useful.

Monad of list in Haskell

I'm trying to make this an instance of Monad in Haskell:
data Parser a = Done ([a], String) | Fail String
Now I try this code to make it an instance of Monad:
instance Functor Parser where
fmap = liftM
instance Applicative Parser where
pure = return
(<*>) = ap
instance Monad Parser where
return xs = Done ([], xs)
Done (xs, s) >>= f = Done (concat (map f xs)), s)
But this obviously doesn't work, because the function f in the bind-function is of the type a -> M b. So the (map f xs) function yields a list of M b-things. It should actually make a list of b's. How can I do this in Haskell?
NOTE: The actual error given by GHC 7.10.3 is:
SuperInterpreter.hs:71:27:
Couldn't match expected type `String' with actual type `a'
`a' is a rigid type variable bound by
the type signature for return :: a -> Parser a
at SuperInterpreter.hs:71:5
Relevant bindings include
xs :: a (bound at SuperInterpreter.hs:71:12)
return :: a -> Parser a (bound at SuperInterpreter.hs:71:5)
In the expression: xs
In the first argument of `Done', namely `([], xs)'
SuperInterpreter.hs:72:45:
Couldn't match type `Parser b' with `[b]'
Expected type: a -> [b]
Actual type: a -> Parser b
Relevant bindings include
f :: a -> Parser b (bound at SuperInterpreter.hs:72:22)
(>>=) :: Parser a -> (a -> Parser b) -> Parser b
(bound at SuperInterpreter.hs:72:5)
In the first argument of `map', namely `f'
In the first argument of `concat', namely `(map f xs)'
Failed, modules loaded: none.
leftaroundabout already showed you some of the problems.
Usually I expect a parser to be some kind of function that takes an input-String, maybe consuming some of this string and then returning an result together with the unconsumed input.
Based on this idea you can extent your code to do just this:
data ParserResult a
= Done (a, String)
| Fail String
deriving Show
data Parser a = Parser { run :: String -> ParserResult a }
instance Functor Parser where
fmap = liftM
instance Applicative Parser where
pure = return
(<*>) = ap
instance Monad Parser where
return a = Parser $ \ xs -> Done (a, xs)
p >>= f = Parser $ \ xs ->
case run p xs of
Done (a, xs') -> run (f a) xs'
Fail msg -> Fail msg
a simple example
here is a simple parser that would accept any character:
parseAnyChar :: Parser Char
parseAnyChar = Parser f
where f (c:xs) = Done (c, xs)
f "" = Fail "nothing to parse"
and this is how you would use it:
λ> run parseAnyChar "Hello"
Done ('H',"ello")
λ> run parseAnyChar ""
Fail "nothing to parse"
While it's not completely uncommon to define fmap = liftM and so on, this is a bit backwards IMO. If you first define the more fundamental instances and base the more involved ones on them, things often come out clearer. I'll leave <*> = ap, but transform everything else:
instance Functor Parser where -- Note that you can `derive` this automatically
fmap f (Done vs rest) = Done (map f vs) rest
fmap f (Fail err) = Fail err
instance Applicative Parser where
pure xs = Done ([], xs)
(<*>) = ap
Now with fmap already present, I can define Monad in the “more mathematical” way: define join instead of >>=.
instance Monad Parser where
return = pure
q >>= f = joinParser $ fmap f q
That means you'll work with intuitively handleable concrete values, rather than having to worry about threading a function through a parser. You can therefore see quite clearly what's going on, just write out the recursion:
joinParser :: Parser (Parser a) -> Parser a
joinParser (Fail err) = Fail err
joinParser (Done [] rest) = Done [] rest
joinParser (Done (Fail err : _) _) = Fail err
joinParser (Done (Done v0 rest0 : pss) rest) = ??
at this point you see clearly what Carsten already remarked: your Parser type doesn't really make sense as a parser. Both the inner and outer Done wrappers somehow have rest data; combining it would mean you combine the undone work... this is not what a parser does.
Search the web a bit, there's plenty of material on how to implement parsers in Haskell. In doubt, look how some established library does it, e.g. parsec.

Do monads not guarantee the applicability of layered/non-layered monadic values to non-layered/non-monadic functions, and is this a good/bad thing?

I'm just trying to get monads, so bear with me if I ask a bad question, but...
If monads only require:
(a -> M a), where M is the monadic type constructor, and
(M a -> (a -> M b) -> M b), which is the bind operation (which I understand as mapping a monad onto a non-monadic to monadic value function)
...doesn't this mean that:
(M a -> a) and
(M (M a) -> M a) are not implicitly required?
Won't this usually cause a problem?
Suppose we have a set of functions, S, which all have the type (x -> y), where x and y are arbitrary types.
Now, suppose I program using a set of monadic functions M, where their types are x -> M y.
Doesn't this mean that once I turn a type into M y, I can't use any of the (x -> y) functions? Or, can I assume that I can do (M x -> (x -> y) -> (y -> M y) -> M y)?
Furthermore, don't we usually want to extract the original type when programming? When switching between something, like async a -> a or maybe a -> a... Isn't that a common operation? I can definitely see the case where somebody wants to optimize a monad out if they see it as negligible (e.g. a logging monad).
Additionally, what about layered monads without flattening? I understand that lists can be seen as monads where restricting flattening is a clear and logical choice, but what about the hypothetical case of async (async a) monadic values where async has no flatten function? Does bind only imply one layer of "monadic reduction" where we can often assume that (M a -> (a -> M a) -> M a) can often be seen as (M a -> (M a -> a) -> (a -> M a) -> M a), and (M M a -> (a -> M a) -> M a or M M a) may not work? Is there a true difference between flattening and non-flattening monads?
Won't this usually cause a problem?
You might say that this is "by design". One of the possible uses is IO; once you have a value tainted with IO, you have to "bubble up"; you can't hide the fact that a function is doing IO under a pure value.
wouldn't that mean I either have to manually convert each (a -> b) -> (a -> M b) by applying a monadic constructor somewhere?
This is easier than you think because every Monad is also a Functor and an Applicative Functor:
randomDice :: IO Int
randomDice = randomRIO (1,6)
cheat :: Int -> Int
cheat = (+1)
main = do
dice <- randomDice
dice' <- cheat <$> randomDice
Having all of the fmap, <$>, liftA/liftM and pure/return machinery at our disposal, it makes it very simple to easily use pure functions in the monadic contexts.
(M (M a) -> M a) is not implicitly required
That one is false. You only need bind to implement it.
join :: (Monad m) => m (m a) -> m a
join x = x >>= id

Unsequence Monad function within Haskell

I'm having some real trouble designing the counterfunction of Haskell's sequence function, which Hoogle tells me doesn't yet exist. This is how it behaves:
ghci> sequence [Just 7, Just 8, Just 9]
Just [7,8,9]
ghci> sequence [getLine, getLine, getLine]
hey
there
stack exchange
["hey","there","stack exchange"] :: IO [String]
My problem is making a function like this:
unsequence :: (Monad m) => m [a] -> [m a]
So that it behaves like this:
ghci> unsequence (Just [7, 8, 9])
[Just 7, Just 8, Just 9]
ghci> sequence getLine
hey
['h','e','y'] :: [IO Char] --(This would actually cause an error, but hey-ho.)
I don't actually know if that's possible, because I'd be escaping the monad at some point, but I've made a start, though I don't know how to set a breakpoint for this recursive function:
unsequence m = (m >>= return . head) : unsequence (m >>= return . tail)
I realise that I need a breakpoint when the m here is equal to return [], but not all monads have Eq instances, so how can I do this? Is this even possible? If so, why and why not? Please tell me that.
You can't have an unsequence :: (Monad m) => m [a] -> [m a]. The problem lies with lists: you can't be sure how may elements you are going to get with a list, and that complicates any reasonable definition of unsequence.
Interestingly, if you were absolutely, 100% sure that the list inside the monad is infinite, you could write something like:
unsequenceInfinite :: (Monad m) => m [a] -> [m a]
unsequenceInfinite x = fmap head x : unsequenceInfinite (fmap tail x)
And it would work!
Also imagine that we have a Pair functor lying around. We can write unsequencePair as
unsequencePair :: (Monad m) => m (Pair a) -> Pair (m a)
unsequencePair x = Pair (fmap firstPairElement x) (fmap secondPairElement x)
In general, it turns out you can only define unsequence for functors with the property that you can always "zip" together two values without losing information. Infinite lists (in Haskell, one possible type for them is Cofree Identity) are an example. The Pair functor is another. But not conventional lists, or functors like Maybe or Either.
In the distributive package, there is a typeclass called Distributive that encapsulates this property. Your unsequence is called distribute there.
It is indeed not possible to create an unsequence function using monads alone. The reason is:
You can safely and easily create a monadic structure from a value using return.
However, it is not safe to remove a value from a monadic structure. For example you can't remove an element from an empty list (i.e. a function of the type [a] -> a is not safe).
Hence we have a special function (i.e. >>=) which safely removes a value from a monadic structure (if one exists), processes it and returns another safe monadic structure.
Hence it is safe to create a monadic structure from a value. However it is not safe to remove a value from a monadic structure.
Suppose we had a function extract :: Monad m => m a -> a which could “safely” remove a value from a monadic structure. We could then implement unsequence as follows:
unsequence :: Monad m => m [a] -> [m a]
unsequence = map return . extract
However, there's no safe way to extract a value from a monadic structure. Hence unsequence [] and unsequence Nothing will return undefined.
You can however create an unsequence function for structures that are both monadic and comonadic. A Comonad is defined as follows:
class Functor w => Comonad w where
extract :: w a -> a
duplicate :: w a -> w (w a)
extend :: (w a -> b) -> w a -> w b
duplicate = extend id
extend f = fmap f . duplicate
A comonadic structure is the opposite of a monadic structure. In particular:
You can safely extract a value from a comonadic structure.
However you can't safely create a new comonadic structure from a value, which is why the duplicate function safely creates a new comonadic structure from a value.
Remember that the definition of unsequence required both return and extract? You can't safely create a new comonadic structure from a value (i.e. comonadic structures don't have return). Hence the unsequence function is defined as follows:
unsequence :: (Comonad m, Monad m) => m [a] -> [m a]
unsequence = map return . extract
Interestingly sequence works on simply monadic structures. So via intuition you might assume that unsequence works on simply comonadic structures. However it not so because you need to first extract the list from the comonadic structure and then put each element of the list into a monadic structure.
The general version of the unsequence function converts a comonadic list structure to a list of monadic structures:
unsequence :: (Comonad w, Monad m) => w [a] -> [m a]
unsequence = map return . extract
On the other hand the sequence function works on simply monadic structures because you are just folding the list of monadic structures into a monadic list structure by chaining all the monads:
import Control.Monad (liftM2)
sequence :: Monad m => [m a] -> m [a]
sequence = foldr (liftM2 (:)) (return [])
Hope that helps.