我想知道,我們如何在 Haskell 函式中做多件事?
例如,我有這個代碼:
number = 0
increment :: Int -> Int
increment i = i 1
function :: String -> String
function s = s " world" AND increment number
我想知道,我們怎么能做這樣的事情?我到處搜索,但找不到這個簡單示例的解決方案:O
number
0
:function "hello"
"hello world" (AND the number = 1 now)
number
1
注意:我知道這AND不是 Haskell 中的語法,但我想讓你明白我想說的話:)
uj5u.com熱心網友回復:
問題是:在haskell中,您沒有像其他編程語言那樣的“可變狀態”:因此“數字= 1”在“設定狀態”方面不起作用
您可以將它們組合起來:
increment :: Int -> Int
increment i = i 1
stringCombine :: String -> String
stringcombine str = str "world"
combine i str = (increment i, stringCombine str)
或者如果你有一個有副作用的函式(比如 print、putStrLn),你必須使用 IO Monad:
doSideEffects :: Int -> String -> IO Int
doSideEffects i str = do
putStrLn $ str "world"
return $ increment i
uj5u.com熱心網友回復:
您不能在 Haskell 中修改變數(實際上它們不是variable)。您可以做的是回傳新值:
f (string, number) = (string " world", number 1)
這將像這樣使用:
Prelude> f ("hello", 0)
("hello world",1)
如果您使用變數而不是文字呼叫此函式,則不會更改該變數的值,因為 Haskell 旨在防止這種情況發生:
Prelude> let n = 0
Prelude> f ("hello", n)
("hello world",1)
Prelude> print n
0
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/330326.html
標籤:哈斯克尔
上一篇:亞馬遜S3暫未找到
