Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: Turtle: get a return value out of a Shell

How do you extract a value out of the Shell monad?

I would like to sequence a list of commands à la bash's &&, but I would also like to extract the final ExitCode value.

Say I have the following code:

import           Turtle

type Commands = [Shell ExitCode]
run :: (MonadIO io) => Commands -> io ExitCode
run cs = whatIsThisFunction $ Prelude.foldl (.&&.) (return ExitSuccess) cs

whatIsThisFunction :: (MonadIO io) => Shell a -> io a
whatIsThisFunction = undefined

I tried to see if I could implement this with Control.Foldl, but did not find a solution.

Any ideas?

More generally, why doesn't Turtle provide a function with such signature:

sh' :: MonadIO io => Shell a -> io a 
like image 672
damien.courousse Avatar asked Aug 27 '17 17:08

damien.courousse


2 Answers

Turtle.Shell provides you with a fold :: MonadIO io => Shell a -> Fold a b -> io b and Control.Foldl gives you a bunch of Folds amongst which: last :: Fold a (Maybe a). You can combine the two to extract the last ExitCode your command returns like so:

import Control.Monad.IO.Class
import Turtle.Shell  as TS
import Control.Foldl as CF

sh' :: MonadIO io => Shell a -> io (Maybe a)
sh' c = TS.fold c CF.last
like image 198
gallais Avatar answered Oct 24 '22 23:10

gallais


sh' :: MonadIO io => Shell a -> io a is not possible because Shell a may be constructed from [a] (evidenced by select :: [a] -> Shell a) which can be empty.

like image 25
erisco Avatar answered Oct 24 '22 21:10

erisco