Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7766191
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T15:21:04+00:00 2026-06-01T15:21:04+00:00

I’ve been working through in Structure and Interpretation of Computer Programs and completing the

  • 0

I’ve been working through in Structure and Interpretation of Computer Programs and completing the exercises in Haskell. The first two chapters were fine (code at github) but Chapter 3 is making me think harder.

It starts by talking about managing state, with the example of a bank account. They define a function make-withdraw by

(define (make-withdraw balance)
    (lambda (amount)
        (if (>= balance amount)
            (begin (set! balance (- balance amount))
                balance)
            "Insufficient funds")))

so that you can execute the following code:

(define w1 (make-withdraw 100))
(define w2 (make-withdraw 100))

(w1 50)
50

(w2 70)
30

(w2 40)
"Insufficient funds"

(w1 40)
10

I’m not sure how I can emulate this in Haskell. I first thought to a some simple function using the State monad:

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)

which allows me to run the code

ghci> runState (do { withdraw 50; withdraw 40 }) 100
(Left "Insufficient funds",30.0)

but that does something different to the scheme code. Ideally I’d be able to run something like

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]

but I’m not sure how to write the function makeWithdraw. Any advice?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T15:21:06+00:00Added an answer on June 1, 2026 at 3:21 pm

    The Scheme code is sneakily using two bits of state: one is the (implicit) association between variables w1 and w2 and a ref-cell; the other is the (explicit) state stored in a ref-cell. There’s a couple different ways to model this in Haskell. For example, we might pull a similar ref-cell trick with ST:

    makeWithdraw :: Float -> ST s (Float -> ST s (Either String Float))
    makeWithdraw initialBalance = do
        refBalance <- newSTRef initialBalance
        return $ \amount -> do
            balance <- readSTRef refBalance
            let balance' = balance - amount
            if balance' < 0
                then return (Left "insufficient funds")
                else writeSTRef refBalance balance' >> return (Right balance')
    

    Which lets us do this:

    *Main> :{
    *Main| runST $ do
    *Main|   w1 <- makeWithdraw 100
    *Main|   w2 <- makeWithdraw 100
    *Main|   x1 <- w1 50
    *Main|   y1 <- w2 70
    *Main|   y2 <- w2 40
    *Main|   x2 <- w1 40
    *Main|   return [x1,y1,y2,x2]
    *Main| :}
    [Right 50.0,Right 30.0,Left "insufficient funds",Right 10.0]
    

    Another option is to make both pieces of the state explicit, for example by associating each account with a unique Int id.

    type AccountNumber = Int
    type Balance = Float
    data BankState = BankState
        { nextAccountNumber :: AccountNumber
        , accountBalance :: Map AccountNumber Balance
        }
    

    Of course, we would then basically be re-implementing the ref-cell operations:

    newAccount :: Balance -> State BankState AccountNumber
    newAccount balance = do
        next <- gets nextAccountNumber
        modify $ \bs -> bs
            { nextAccountNumber = next + 1
            , accountBalance = insert next balance (accountBalance bs)
            }
        return next
    
    withdraw :: Account -> Balance -> State BankState (Either String Balance)
    withdraw account amount = do
        balance <- gets (fromMaybe 0 . lookup account . accountBalance)
        let balance' = balance - amount
        if balance' < 0
            then return (Left "insufficient funds")
            else modify (\bs -> bs { accountBalance = insert account balance' (accountBalance bs) }) >> return (Right balance')
    

    Which would then let us write makeWithdraw:

    makeWithDraw :: Balance -> State BankState (Balance -> State BankState (Either String Balance))
    makeWithdraw balance = withdraw <$> newAccount balance
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a jquery bug and I've been looking for hours now, I can't
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
In my XML file chapters tag has more chapter tag.i need to display chapters
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
I'm working with an upstream system that sometimes sends me text destined for HTML/XML
I am trying to loop through a bunch of documents I have to put
I'm making a simple page using Google Maps API 3. My first. One marker
That's pretty much it. I'm using Nokogiri to scrape a web page what has

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.