का अध्याय 3 मैं Structure and Interpretation of Computer Programs में काम कर रहा हूं और हास्केल में अभ्यास पूरा कर रहा हूं। पहले दो अध्याय ठीक थे (github पर कोड) लेकिन अध्याय 3 मुझे कठिन सोच रहा है।प्रबंधन राज्य - एसआईसीपी
यह बैंक खाते के उदाहरण के साथ राज्य के प्रबंधन के बारे में बात करके शुरू होता है।
(define w1 (make-withdraw 100))
(define w2 (make-withdraw 100))
(w1 50)
50
(w2 70)
30
(w2 40)
"Insufficient funds"
(w1 40)
10
मुझे यकीन है कि कैसे मैं हास्केल में इस का अनुकरण कर सकते हैं नहीं कर रहा हूँ: इतना है कि आप निम्नलिखित कोड निष्पादित कर सकते हैं वे द्वारा
(define (make-withdraw balance)
(lambda (amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds")))
एक समारोह make-withdraw
परिभाषित करते हैं। मैं पहली बार एक के लिए कुछ सरल समारोह राज्य इकाई का उपयोग कर सोचा: जो मुझे कोड
ghci> runState (do { withdraw 50; withdraw 40 }) 100
(Left "Insufficient funds",30.0)
चलाने की अनुमति देता
import Control.Monad.State
type Cash = Float
type Account = State Cash
withdraw :: Cash -> Account (Either String Cash)
withdraw amount = state makewithdrawal where
makewithdrawal balance = if balance >= amount
then (Right amount, balance - amount)
else (Left "Insufficient funds", balance)
लेकिन है कि कुछ योजना कोड के लिए अलग करता है। आदर्श रूप में मैं
do
w1 <- makeWithdraw 100
w2 <- makeWithdraw 100
x1 <- w1 50
y1 <- w2 70
y2 <- w2 40
x2 <- w1 40
return [x1,y1,y2,x2]
[Right 50,Right 70,Left "Insufficient funds",Right 40]
की तरह कुछ चलाने के लिए सक्षम हो जाएगा, लेकिन मुझे यकीन है कि कैसे समारोह makeWithdraw
लिखने के लिए नहीं कर रहा हूँ। कोई सलाह?
धन्यवाद, यह एक अच्छा जवाब है। –