Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(SourceT): add fromConsumableActionStep that creates a StepT from… #1533

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions changelog.d/generalize-fromActionStep-to-consumable
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
synopsis: Add a `StepT` constructor method that consumes a resource
prs: #1533
issues: #1448

description: {

`fromActionStep` always runs the same action, which makes it impossible with such monadic actions to
"consume" a resource (that is to say to pass the modified resource to the following action), or
"unfold" an input structure.

`unfoldStep` gives this possibility.

This allows for example to build a `StepT m` directly from a `Streaming.Prelude.Stream`, by passing
`unfoldStep` the following argument:

```haskell
import Streaming.Prelude as S

action :: Stream (Of a) m r -> m (Maybe ( a, Stream (Of a) m r ))
action = S.uncons
```
}
23 changes: 23 additions & 0 deletions servant/src/Servant/Types/SourceT.hs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
module Servant.Types.SourceT where

import Control.Monad.Except
Expand Down Expand Up @@ -312,6 +313,28 @@ fromActionStep stop action = loop where
| otherwise = Yield x loop
{-# INLINE fromActionStep #-}

-- | Create a `StepT' from a consumable @c@, that is to say from an input and an action that returns
-- and is called again on an updated version of that input.
giulioforesto marked this conversation as resolved.
Show resolved Hide resolved
--
-- >>> import qualified Streaming.Prelude as S
-- >>> foreachStep mempty print (unfoldStep S.uncons $ S.each [1..3] :: StepT IO Int)
-- 1
-- 2
-- 3
--
unfoldStep :: Functor m
=> (c -> m (Maybe (a,c)))
-- ^ Action. Return @Nothing@ to stop or @Just (a,c)@ where @a@ is the
-- output element of the action and @c@ the updated input
-> c
-- ^ Input
-> StepT m a
unfoldStep action = loop where
loop c = Effect $ step <$> action c
step Nothing = Stop
step (Just (x,t)) = Yield x $ loop t
{-# INLINE unfoldStep #-}

-------------------------------------------------------------------------------
-- File
-------------------------------------------------------------------------------
Expand Down