on master help sign in
Add notes for creating arrays from pure streams
commit348a4e12723196b1eca5af7c9bef42de48c45dc8 authorHarendra Kumar <harendra@composewell.com> dateSun 5 Jun 2022, 23:37 (4 years ago) parent0e739d7
1 file changed+26
core/src/Streamly/Data/Array/Foreign.hs+26
core/src/Streamly/Data/Array/Foreign.hs+26
@@ -24,6 +24,23 @@
2424--
2525-- = Programmer Notes
2626--
27+-- Array creation APIs require a 'MonadIO' Monad, except 'fromList' which is a
28+-- pure API. To operate on streams in pure Monads like 'Identity' you can hoist
29+-- it to IO monad as follows:
30+--
31+-- >>> import Data.Functor.Identity (Identity, runIdentity)
32+-- >>> s = Stream.fromList [1..10] :: SerialT Identity Int
33+-- >>> s1 = Stream.hoist (return . runIdentity) s :: SerialT IO Int
34+-- >>> Stream.fold Array.write s1 :: IO (Array Int)
35+-- [1,2,3,4,5,6,7,8,9,10]
36+--
37+-- 'unsafePerformIO' can be used to get a pure API from IO, as long as you know
38+-- it is safe to do so:
39+--
40+-- >>> import System.IO.Unsafe (unsafePerformIO)
41+-- >>> unsafePerformIO $ Stream.fold Array.write s1 :: Array Int
42+-- [1,2,3,4,5,6,7,8,9,10]
43+--
2744-- To apply a transformation to an array use 'read' to unfold the array into a
2845-- stream, apply a transformation on the stream and then use 'write' to fold it
2946-- back to an array.
@@ -76,3 +93,12 @@ module Streamly.Data.Array.Foreign
7693where
7794
7895import Streamly.Internal.Data.Array.Foreign as A
96+
97+-- $setup
98+-- >>> :m
99+-- >>> :set -XFlexibleContexts
100+-- >>> :set -package streamly
101+-- >>> import Streamly.Prelude (SerialT)
102+-- >>> import Streamly.Data.Array.Foreign (Array)
103+-- >>> import qualified Streamly.Internal.Data.Stream.IsStream as Stream
104+-- >>> import qualified Streamly.Data.Array.Foreign as Array