1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2006
    Rep Power

    Scheme: calculating binary


    I'm having a little problem while trying to make a piece of code that can turn a number into its binary code.

    (define (displ-as-bin n)
    (cond ((< n 1) (display " "))
    ((even? n) ((displ "0")(displ-as-bin (quotient n 2))))
    (else ((display "1")(displ-as-bin (quotient n 2))))))

    When trying it out, it gives me the correct answer, followed by an error, that I can't seem to fix!

    For example:

    (displ-as-bin 8 )
    0001 . procedure application: expected procedure, given: #<void>; arguments were: #<void>

    I can't figure out why I'm getting this error, so if anyone with a bit of Scheme knowledge could help me out here, it would be very much appreciated. Thanks =)
  2. #2
  3. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Hull, UK
    Rep Power

    You're trying to apply the return value of display which is #<void>. You can fix the code very simply by removing the brackets that are around this (to stop the application).

    Here is the fixed code:

    scheme Code:
    (define (display-as-binary n)
      (cond ((>= n 1)
             (display (if (even? n)
                 (quotient n 2)))))

    Notice how display and display-as-binary are both grouped within the conditions body automatically, there is no need for extra brackets .

    Take care,

    programming language development: www.netytan.com Hula

  4. #3
  5. Commie Mutant Traitor
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Jun 2004
    Alpharetta, GA
    Rep Power
    Conversely, you could use (begin) to allow mutiple lines of code on a single (if) statement:
    scheme Code:
    (define (display-as-binary n)
      (if (>= n 1)
             (quotient n 2))
            (display (if (even? n)

    (Note that this prints the results in the correct order, too... however, it would make still more sense to generalize the code, by returning a string instead of simply displaying the value.)
    Rev First Speaker Schol-R-LEA;2 JAM LCF ELF KoR KCO BiWM TGIF
    #define KINSEY (rand() % 7) λ Scheme is the Red Pill
    Scheme in Short Understanding the C/C++ Preprocessor
    Taming Python A Highly Opinionated Review of Programming Languages for the Novice, v1.1

    FOR SALE: One ShapeSystem 2300 CMD, extensively modified for human use. Includes s/w for anthro, transgender, sex-appeal enhance, & Gillian Anderson and Jason D. Poit clone forms. Some wear. $4500 obo. tverres@et.ins.gov

IMN logo majestic logo threadwatch logo seochat tools logo