[英]Purescript: How to read a string from stdin and save it?
我對 Purescript 很陌生,我正在嘗試處理一些用戶輸入(從 stdin 接收),但我最好的方法是這個:
processInput :: String -> Effect Unit
processInput input = do
let
arr = split (Pattern " ") input
player1 = unsafeIndex arr 0
player2 = unsafeIndex arr 1
result = checkGame player1 player2
log $ "You typed: " <> player1 <> " " <> player2 <> ":" <> show (result)
lineHandler :: Interface -> String -> Effect Unit
lineHandler interface s = do
if s == "quit"
then do
close interface
else do
processInput s
prompt interface
main :: Effect Unit
main = do
interface <- createConsoleInterface noCompletion
setPrompt "> " interface
setLineHandler (lineHandler interface) interface
prompt interface
我在其中使用 Node.ReadLine package 創建一個接口,請求輸入並以另一種方法處理它。 這適用於石頭剪刀布游戲,我設法獲得了一次移動的結果並將其記錄給用戶。 但我堅持將該result
添加到 lineHandler function 之外的總數。
有沒有其他方法可以從main
scope(沒有 lineHandler)處的用戶獲取字符串輸入? 或者有沒有一種方法可以定義在 lineHandler 執行過程中累積的參數points
?
想到了State,還是不是很明白。 提前致謝
如果您想將程序構造為來自Node.ReadLine
的Interface
,則必須將游戲 state(無論它是什么)保存在可變的 memory 單元格中,該單元格由Ref
類型表示。 您可以使用new
的 function創建這樣的單元格,然后分別使用read
和write
函數對其進行讀取和寫入。
您必須在main
中創建 memory 單元格,然后通過lineHandler
將其隧道傳輸到processInput
。
processInput :: Ref.Ref Int -> String -> Effect Unit
processInput total input = do
let
arr = split (Pattern " ") input
player1 = unsafePartial $ unsafeIndex arr 0
player2 = unsafePartial $ unsafeIndex arr 1
result = checkGame player1 player2
currentTotal <- Ref.read total -- Read from the cell
let newTotal = currentTotal + 42
Ref.write newTotal total -- Write new value to the cell
log $ "You typed: " <> player1 <> " " <> player2 <> ": " <> show (result) <> ", current total is " <> show newTotal
lineHandler :: Ref.Ref Int -> Interface -> String -> Effect Unit
lineHandler total interface s = do
if s == "quit"
then do
close interface
else do
processInput total s
prompt interface
main :: Effect Unit
main = do
total <- Ref.new 0 -- Create a new memory cell with initial value of 0
interface <- createConsoleInterface noCompletion
setPrompt "> " interface
setLineHandler (lineHandler total interface) interface
prompt interface
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.