Haskell Infinite Type - haskell

I'm trying to get the code below working. It's a finite state machine where I pass in a function-as-next-state. The function is called with r and returns a list of results + the next function-as-next state. Keep on calling until the list runs out, and return the concatenation of the results. The monad is an error monad to allow me to throw an error if needed.
fsm f [] = return []
fsm f (r:rs) = do
(xs, f') <- f r
rest <- fsm f' rs
return $ xs ++ rest
The error is:
Occurs check: cannot construct the infinite type: t1 = t0 -> m0 ([a0], t1)
In the first argument of `fsm', namely f'
I've seen the infinite type error before and I understand the way around it is to wrap a type with a newtype. But I cannot figure out how to get this done.
Can someone point out the insight?

I think this is what you want:
newtype F m = F { unF :: String -> m ([String], F m) }
fsm :: (Monad m) => F m -> [String] -> m [String]
fsm f [] = return []
fsm f (r:rs) = do
(xs, f') <- unF f r
rest <- fsm f' rs
return $ xs ++ rest
You are right that you need to use a data or newtype any time you want a recursive type.
In reply to your comment, here's how you would implement your dup function:
dup :: (Monad m) => F m
dup = F dup' where dup' xs = return ([xs, xs], F dup')
... or you could split it up into two separate definitions if you prefer.
Note that if you are not sure what the type signature should be, just enable the NoMonomorphismRestriction extension and the compiler will not complain and correctly infer the top-level type for you.

Related

What would an idiomatic, monadic version of maximumBy look like?

How can I get a maximum element of an effectful container where computing attribute to compare against also triggers an effect?
There has to be more readable way of doing things like:
latest dir = Turtle.fold (z (ls dir)) Fold.maximum
z :: MonadIO m => m Turtle.FilePath -> m (UTCTime, Turtle.FilePath)
z mx = do
x <- mx
d <- datefile x
return (d, x)
I used overloaded version rather than non-overloaded maximumBy but the latter seems better suite for ad-hoc attribute selection.
How can I be more methodic in solving similar problems?
So I know nothing about Turtle; no idea whether this fits well with the rest of the Turtle ecosystem. But since you convinced me in the comments that maximumByM is worth writing by hand, here's how I would do it:
maximumOnM :: (Monad m, Ord b) => (a -> m b) -> [a] -> m a
maximumOnM cmp [x] = return x -- skip the effects if there's no need for comparison
maximumOnM cmp (x:xs) = cmp x >>= \b -> go x b xs where
go x b [] = return x
go x b (x':xs) = do
b' <- cmp x'
if b < b' then go x' b' xs else go x b xs
I generally prefer the *On versions of things -- which take a function that maps to an Orderable element -- to the *By versions -- which take a function that does the comparison directly. A maximumByM would be similar but have a type like Monad m => (a -> a -> m Ordering) -> [a] -> m a, but this would likely force you to redo effects for each a, and I'm guessing it's not what you want. I find *On more often matches with the thing I want to do and the performance characteristics I want.
Since you're already familiar with Fold, you might want to get to know FoldM, which is similar.
data FoldM m a b =
-- FoldM step initial extract
forall x . FoldM (x -> a -> m x) (m x) (x -> m b)
You can write:
maximumOnM ::
(Ord b, Monad m)
=> (a -> m b) -> FoldM m a (Maybe a)
maximumOnM f = FoldM combine (pure Nothing) (fmap snd)
where
combine Nothing a = do
f_a <- f a
pure (Just (f_a, a))
combine o#(Just (f_old, old)) new = do
f_new <- f new
if f_new > f_old
then pure $ Just (f_new, new)
else pure o
Now you can use Foldl.foldM to run the fold on a list (or other Foldable container). Like Fold, FoldM has an Applicative instance, so you can combine multiple effectful folds into one that interleaves the effects of each of them and combines their results.
It's possible to run effects on foldables using reducers package.
I'm not sure if it's correct, but it leverages existing combinators and instances (except for Bounded (Maybe a)).
import Data.Semigroup.Applicative (Ap(..))
import Data.Semigroup.Reducer (foldReduce)
import Data.Semigroup (Max(..))
import System.IO (withFile, hFileSize, IOMode(..))
-- | maxLength
--
-- >>> getMax $ maxLength ["abc","a","hello",""]
-- 5
maxLength :: [String] -> (Max Int)
maxLength = foldReduce . map (length)
-- | maxLengthIO
--
-- Note, this runs IO...
--
-- >>> (getAp $ maxLengthIO ["package.yaml", "src/Lib.hs"]) >>= return . getMax
-- Just 1212
--
-- >>> (getAp $ maxLengthIO []) >>= return . getMax
-- Nothing
maxLengthIO :: [String] -> Ap IO (Max (Maybe Integer))
maxLengthIO xs = foldReduce (map (fmap Just . f) xs) where
f :: String -> IO Integer
f s = withFile s ReadMode hFileSize
instance Ord a => Bounded (Maybe a) where
maxBound = Nothing
minBound = Nothing

Define bind without join for the list monad in Haskell

I understand the definition of >>= in term of join
xs >>= f = join (fmap f xs)
which also tells us that fmap + join yields >>=
I was wondering if for the List monad it's possible to define without join, as we do for example for Maybe:
>>= m f = case m of
Nothing -> Nothing
Just x -> f x
Sure. The actual definition in GHC/Base.hs is in terms of the equivalent list comprehension:
instance Monad [] where
xs >>= f = [y | x <- xs, y <- f x]
Alternatively, you could try the following method of working it out from scratch from the type:
(>>=) :: [a] -> (a -> [b]) -> [b]
We need to handle two cases:
[] >>= f = ???
(x:xs) >>= f = ???
The first is easy. We have no elements of type a, so we can't apply f. The only thing we can do is return an empty list:
[] >>= f = []
For the second, x is a value of type a, so we can apply f giving us a value of f x of type [b]. That's the beginning of our list, and we can concatenate it with the rest of the list generated by a recursive call:
(x:xs) >>= f = f x ++ (xs >>= f)

Haskell sequencelistIO [a -> IO a] -> a -> IO a

I have the following problem:
I have a task to write a function taking a list of IO interactions and an initial value. The first action takes the initial value as an argument and the function shall pass its result (IO a) as an argument to the next interaction.
The latter expects data of type a, not IO a.
I don't get how to come over this obstacle.
Here is what I have:
seqList :: [a -> IO a] -> a -> IO a
seqList [] n = return n
seqList (inter:inters) n = do
val <- inter n
return $ seqList inters val
The problem is that val is of type (IO a) but the next IO expects a.
I tried something like
tmp <- unsafePerformIO val
after val <- ...
but that does not help and would be really bad style.
How can I solve this problem?
I want hints, no solutions,
thanks in advance.
EDIT
I edited it the following way:
seqList :: [a -> IO a] -> a -> IO a
seqList [] n = return n
seqList (inter:inters) n = do
val <- inter n
seqList inters val
as seqList inters val is already of the right type.
This should be ok or am I mistaken? It actually works for my examples.
I still am very new to this whole do-notation-monads-io-stuff as it seems.
Thank you very much for the hints.
The edited version is correct.
There's an interesting way of looking at this problem, though. One might analyze the type as follows
type Thing a = a -> IO a
seqList :: [Thing a] -> Thing a
In other words, seqList is a mechanism for combining Things. If we rewrite your working code a bit we can emphasize this.
seqList :: [Thing a] -> Thing a
seqList [] n = neutralThing n
seqList (thingHere : restOfThings) n = do
let remainingThing = seqList restOfThings
val <- thingHere
remainingThing val
neutralThing :: Thing a
neutralThing a = return a
In particular, I've isolated three parts
The neutral thing which is returned when the input list is empty
The recursive bit which computes the "remaining thing" from the tail of the list
The actual do-notation bit which "combines" things.
We can go even further
seqList :: [Thing a] -> Thing a
seqList [] = neutralThing
seqList (thingHere : restOfThings) =
combineThings thingHere (seqList restOfThings)
neutralThing :: Thing a
neutralThing a = return a
combineThings :: Thing a -> Thing a -> Thing a
combineThings thing1 thing2 n = do
n' <- thing1 n
n'' <- thing2 n'
return n''
Now we can recognize a general pattern: seqList is just a fold over the list.
seqList :: [Thing a] -> Thing a
seqList = foldr combineThings neutralThing
If we recognize that folds often expose Monoids we can also detect how Thing a is a monoid for any choice of a
memptyThing :: Thing a
memptyThing = neutralThing
mappendThing :: Thing a -> Thing a -> Thing a
mappendThing = combineThings
Finally, if we're really clever, we can note that Thing inherits it monoidalness from the slightly more general construction of a Category—in particular, something called the Kleisli IO category. If we were to use the Kleisli type itself there would be a lot of wrapping and unwrapping, but instead we can examine the types of return and (>=>) from Control.Monad.
return :: Monad m => a -> m a
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> (a -> m c)
With a little care we can see that these types are compatible with memptyThing and mappendThing. So, an ultimate solution to your problem is as follows
seqList :: [Thing a] -> Thing a
seqList = foldr (>=>) return
and we can finally note that this has a more general type if we like
seqList :: Monad m => [a -> m a] -> (a -> m a)
seqList = foldr (>=>) return
Another way to think of it is this: if you had two such actions, how would you chain them together? There's an operator in the Control.Monad library that does that. It shouldn't be too hard to understand:
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c
f >=> g = \a -> do
b <- f a
g b
And if you have that operator, then you can write seqList by taking the the list of actions and basically putting >=> between all of them. The standard foldr function, will do the trick; as the documentation says it does precisely that:
foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...)
So put those together, plus return for the empty list case, and you get:
import Control.Monad ((>=>))
seqList :: [a -> IO a] -> a -> IO a
seqList actions = foldr (>=>) return actions
Whose behavior can be described by these equations:
foldr (>=>) return [] == return
foldr (>=>) return [x1, ..., xn] == x1 >=> ... >=> xn >=> return
And let's work it out in more detail! The definition of foldr is this:
foldr :: (a -> b -> b) -> b -> [a] -> b
foldr _ z [] = z
foldr f z (x:xs) = f x (foldr f z xs)
So using that, we can rewrite my definition of seqList as such:
-- Use the definition of `foldr` to split this into two cases
seqList [] = return
seqList (action:actions) = action >=> foldr (>=>) return actions
-- Use the definition of `>=>` to spell out the second equation
seqList [] = return
seqList (action:actions) = \a -> do
val <- action a
foldr (>=>) return actions val
-- But by the definition of `seqList`, we can rewrite the last line
-- to this:
seqList [] = return
seqList (action:actions) = \a -> do
val <- action a
seqList actions val
And that's what you wrote on your second try!
Some hints:
Consider the case of having exactly 2 functions in your list and have a look at >=>.
Have a look at the Endo monoid, in particular at the signature of its mconcat. Try replacing Endo a with a -> a in the signature.
How would the instance of the monadic generalization of Endo
newtype EndoM m a = EndoM { appEndoM :: a -> m a }
look like? What would be its mempty and mappend? What would be its mconcat?

Circular programming - replace list elements by minimum value

I've just read this article about circular programming. It seems so alien to me. Although I can imagine the feedback as lazily evaluated thunk that will be evaluated to desired result later, just can't wrap my head around it. So I decided to write function that replaces every element of a list with it's minimum value.
trace :: (a -> c -> (b,c)) -> a -> b
trace f a = b
where (b,c) = f a c
repminList :: (Num a, Ord a) => [a] -> [a]
repminList = trace repIIminList
repIIminList [x] m = ([m], x)
repIIminList (a:as) m = let (replaced, m) = repIIminList as m
in (m : replaced, min a m)
But repminList [1,2,3] equals to [2,3,3]. What would be the correct version?
Your problem is that you have two different m variables and one shadows over the other so you don't end up using the actual circular variable at all. Here's the fixed version of your repIIminList:
repIIminList [x] m = ([m], x)
repIIminList (a:as) m = let (replaced, m') = repIIminList as m
in (m : replaced, min a m')
Here m is the final, smallest element of the list that you receive as circular parameter. The m' returned from the recursive call to repIIminList is the smallest value seen so far, so it's important that you append the final smallest value (i.e. m) to the result list and then update the current smallest value by returning min a m'.
That's a pretty cool technique! Here's a working program that's inspired by yours (I didn't really read the article except to glance at the picture, so this may not be exactly what the author intended, but it works):
looper :: (inputT -> feedfwdT -> feedbackT -> (feedbackT, outputT)) -> inputT -> feedfwdT -> outputT
looper f input primer = output
where (feedback, output) = f input primer feedback
min_feedback :: (Ord a) => [a] -> Maybe a -> a -> (a, [a])
min_feedback [] (Just p) _ = (p, [])
min_feedback (x:xs) partial_min minimum = (feedback, minimum:output)
where new_partial_min = case partial_min
of Nothing -> Just x
Just p -> Just $ min x p
(feedback, output) = min_feedback xs new_partial_min minimum
min_looped :: (Ord a) => [a] -> [a]
min_looped input = looper min_feedback input Nothing
main = print $ min_looped [1,4,6,2,6,3,-1,6,3,6,10]
The key here is that you need more than the feedback channel, you also need a feedforward channel to determine the minimum value on the first pass through the loop. My ASCII art skills are not up to the standard set in the article, so you'll just have to make do with this paint drawing:
The feedforward is the minimum value seen so far in the list. The primer kickstarts the feedforward channel. The feedback channel takes the result value from the feedforward channel back up to the start of the list. Finally the feedback value becomes the minimum value that gets used to fill the output list.
It's
repIIminList (x:[]) m' = ([m'], x)
repIIminList (x:xs) m' = (m' : xs', min x m) where (xs', m) = repIIminList xs m'
m is a current minimum, m' is a final minimum, xs is a current list, xs' is a final list. That is, repIIminList receives a list and a number and recursively replaces every element in a list with this number. repIIminList also computes the minimum of the list. trace applies repIIminList to the minimum, computed by repIIminList itself.
Using the state monad you can rewrite this in a pretty explicit way:
repminList :: [Int] -> [Int]
repminList [] = []
repminList (x:xs) = evalState (go xs) x where
go [] = get >>= return . (:[])
go (x:xs) = modify (min x) >> flip (:) <$> go xs <*> get
Or using CPS style directly:
repminList :: [Int] -> [Int]
repminList [] = []
repminList (x:xs) = foldr (\x r -> (\(x:xs) -> x:x:xs) . r . min x) (:[]) xs x
I'm too tired to analyze your code, divine your intent and the bug. However, I'll happily show you how I avoid having to think that hard when doing basic knot tying.
Its this State Monad, yay! My use of the State monad (below) is just a little plumbing that keeps track of a single current value in a manner that allows the value to be looked-up and updated.
repMin kicks off the computation by taking into account the empty list then running the state monad.
Our worker action f is provided with the input list and the minimum element in the list (currently a thunk, do not evaluate!)
f traverses the list computing the minimum on the way and replacing each element with the soon-to-be-known-but-not-yet-evaluatable minimum value m.
The code:
import Control.Monad.State
repMin :: [Int] -> [Int]
repMin [] = []
repMin xs#(x:_) = let (v,m) = runState (f m xs) x in v
f :: Int -> [Int] -> State Int [Int]
f m xs = mapM (λx -> checkMin x >> return m) xs
where
checkMin :: Int -> State Int ()
checkMin x = modify (min x)
Notice there's a lazyness leak here wrt our huge thunk of min a (min b ( min c ...))), but you get the picture.

List Iterator using ContT

I have a simple list that I would like to iterate over "yield"ing between each element and printing that element to the output. I am trying to use the ContT monad to do this but running into issues. Here's what I have so far:
data K a = Nil | K (a,() -> K a)
listIterator :: (Monad m) => [r] -> m (K r)
listIterator [] = return Nil
listIterator (x:xs) = return (ContT (\k -> K (x,k))) >> listIterator xs
runIterator :: IO ()
runIterator = do
a <- listIterator ([1,2,3] :: [Int])
let loop Nil = liftIO $ print "nil"
loop (K (curr,newI)) =
do
liftIO $ print curr
loop (newI ())
loop a
The expected output is:
1
2
3
nil
What I get is:
nil
Any help is appreciated!
listIterator (x:xs) = return (ContT (\k -> K (x,k))) >> listIterator xs
does not do what you expect, equational reasoning
listIterator (x:xs)
= return (ContT (\k -> K (x,k))) >> listIterator xs
= (return (ContT (\k -> K (x,k)))) >>= \_ -> listIterator xs
= (\_ -> listIterator xs) (ContT (\k -> K (x,k)))
= listIterator xs
I'm not sure exactly why you want to use an iterator. Haskell is already lazy, so iteration patterns like this are mostly used only when you have resource management issues that need to interact well with a demand driven usage pattern. And, you don't need the continuation monad at all:
Instead of writing the K constructor to take a tuple it is more idiomatic to
data K a = Nil | K a (() -> K a)
intuitively, the type for the listIterator does not use its monadic structure: it just constructs a value, so
listIterator ::[r] -> K r
listIterator [] = Nil
listIterator (x:xs) = K x (\_ -> listIterator xs)
now life is trivial
runIterator :: IO ()
runIterator = do
let a = listIterator ([1,2,3] :: [Int])
loop Nil = liftIO $ print "nil"
loop (K curr newI) =
do
liftIO $ print curr
loop (newI ())
loop a
which would probably be best to write without the use of do notation.
This may not be the answer you were looking for, but if you are interested in this style of programming, you should look into pipes and similar libraries. (conduit is the rising star in the "real world", but pipes provides a simpler tool for teaching which is why I use it here.)
$ cabal update && cabal install pipes
Pipes are like iterators, except they come in three flavors: those that can acquire input (Consumers), those that produce output (Producers), and those that do both (Pipes). If you connect pipes such that the input and output ends are all satisfied, then it is called a "Pipeline", and it is a self-contained unit that can be run without any additional input.
Pipe provides a monad instance for convenience in creating pipes. The >+> operator connects two pipes together.
import Control.Pipe
import Control.Monad.Trans.Class
import Control.Monad.IO.Class
-- annoyingly, Pipe does not provide a MonadIO instance
instance (MonadIO m) => MonadIO (Pipe a b m) where
liftIO = lift . liftIO
listIterator :: Monad m => [a] -> Producer (Maybe a) m ()
listIterator (x:xs) = yield (Just x) >> listIterator xs
listIterator [] = yield Nothing
printer :: (MonadIO m, Show a) => Consumer (Maybe a) m ()
printer = do
mx <- await
case mx of
Just x -> liftIO (print x) >> printer
Nothing -> liftIO (putStrLn "nil")
main = runPipe $ listIterator [1, 2, 3] >+> printer
The source for Control.Pipe is delightfully simple, especially if you have been reading Gabriel's recent blog posts about Free monads, particularly Why free monads matter and Purify code using free monads.

Resources