on master help sign in
Add notes for creating arrays from pure streams
348a4e1Harendra Kumar
core/src/Streamly/Data/Array/Foreign.hs+26
@@ -24,6 +24,23 @@
24--
24--
25-- = Programmer Notes
25-- = Programmer Notes
26--
26--
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+--
27-- To apply a transformation to an array use 'read' to unfold the array into a
44-- To apply a transformation to an array use 'read' to unfold the array into a
28-- stream, apply a transformation on the stream and then use 'write' to fold it
45-- stream, apply a transformation on the stream and then use 'write' to fold it
29-- back to an array.
46-- back to an array.
@@ -76,3 +93,12 @@ module Streamly.Data.Array.Foreign
76where
93where
77
94
78import Streamly.Internal.Data.Array.Foreign as A
95import 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