나는 Structure and Interpretation of Computer Programs에서 일하고 있으며 하스켈에서 연습을 마쳤습니다. 첫 번째 두 장은 괜찮 았지만 (코드는 github) 3 장은 나를 더 열심히 생각하게 만듭니다.상태 관리 - SICP의 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
을 정의합니다. 나는 처음에 국가 모나드를 사용하여 몇 가지 간단한 기능을 생각 :
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)
나 코드
ghci> runState (do { withdraw 50; withdraw 40 }) 100
(Left "Insufficient funds",30.0)
을 실행할 수 있지만 그 계획 코드에 다른 일을한다. 이상적으로는
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
를 작성하는 방법을 모르겠어요. 어떤 충고?
감사합니다. 훌륭한 답변입니다. –