-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy path05-ReadLine-Aff.purs
65 lines (49 loc) · 1.83 KB
/
05-ReadLine-Aff.purs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
module ConsoleLessons.ReadLine.AffMonad where
import Prelude
import Effect (Effect)
import Effect.Console (log)
import Node.ReadLine ( Interface
, createConsoleInterface, noCompletion
, question, close)
import Data.Either (Either(..))
-- new imports
-- This will lift the `Effect` monad into another monad context (i.e. Aff),
-- enabling us to use `log` from Effect in an `Aff` monad context.
import Effect.Class (liftEffect)
import Effect.Aff (Aff, runAff_, makeAff, nonCanceler)
createInterface :: Effect Interface
createInterface = do
log "Creating interface..."
interface <- createConsoleInterface noCompletion -- no tab completion
log "Created!\n"
pure interface
closeInterface :: Interface -> Effect Unit
closeInterface interface = do
log "Now closing interface"
close interface
log "Finished!"
useInterface :: Interface -> Aff Unit
useInterface interface = do
-- lifting `log`'s output into an Aff monad context
liftEffect $ log $ "Requesting user input..."
-- querying user for info and waiting until receive user input
answer <- question' "Type something here: " interface
liftEffect $ log $ "You typed: '" <> answer <> "'\n"
-- This is `affQuestion` from earlier
question' :: String -> Interface -> Aff String
question' message interface = makeAff go
where
-- go :: (Either Error a -> Effect Unit) -> Effect Canceler
go raRF = question message (raRF <<< Right) interface $> nonCanceler
main :: Effect Unit
main = do
log "\n\n" -- separate output from program
interface <- createInterface
runProgram interface
runProgram :: Interface -> Effect Unit
runProgram interface = {-
runAff_ :: forall a. (Either Error a -> Effect Unit) -> Aff a -> Effect Unit -}
runAff_
-- Ignore any errors and output and just close the interface
(\_ -> closeInterface interface)
(useInterface interface)