I'm trying to emulate a stack in scheme. I'm using DrScheme and I select the language R5RS. I need to create functions that pop, push, and peek. But i'm having trouble figuring out how to pass by refe开发者_如何学编程rence. I've read some information about boxes, but they are not supported in R5RS. Is there any other way to pass by reference?
Short answer: don't use r5rs; just use the native language. In current versions of DrRacket, that language is called "racket". Here's a program that uses boxes:
#lang racket
(define b (box 234))
(set-box! b 333)
(unbox b)
FWIW: Greg's answer is more purely functional than mine, but it would be a mistake to believe that mutable structures are not available in DrRacket (nee DrScheme).
Finally finally, you're misusing the term "call by reference". Boxes are just mutable structures, and a call-by-value language (such as racket, r5rs, java, etc.) can mutate these structures just fine.
Instead of passing "by reference", which is something you might do in an imperative language, Scheme encourages you to think in a functional sense. This means that your push
operation, for example, would take two parameters:
- a stack
- a new element
and return a new stack that contains the new element in combination with the rest of the existing stack. Similarly, the pop
operation would take a stack and return one with the top element gone, and peek
would return the value of the top element.
As it turns out, lists in Scheme work almost exactly like stacks. The following mappings will help you get started:
- push - cons
- pop - rest
- peek - first
精彩评论