【问题标题】:How to define a string in Scheme - any string that I choose?如何在 Scheme 中定义一个字符串 - 我选择的任何字符串?
【发布时间】:2012-12-16 14:55:24
【问题描述】:

鉴于:

(define output "")

或者那个

(define output "goodInput")

当我在我的代码中运行这些定义时,我得到:

ERROR: In procedure memoization:
ERROR: Bad define placement (define output "").

这是为什么呢?

编辑:

; Formal function of the code
(define (double->sum myString)

(define myVector 0)
(set! myVector (breaking myString))
(define output "")
(define returnValue  (checkLegit myVector)) ; check the number of legitimate characters ,they need to be either numbers or "."
(define flag 0)   
(if (not(= returnValue (vector-length myVector))) (set! output "Input error") (set! flag (+ flag 1)))

(define i 0)            ; the length of the vector
(define count 0)        ; the value of all the numbers in the vector

(if 
    (= flag 1)

(do ()                             
  ((= i (vector-length myVector))) ; run until the end of the vector
  (cond 
    ((char=? (vector-ref myVector i) #\.) ; check if we found a dot 
               (set! output (appending output count))    (set! output (appendingStrings output ".")) (set! count 0)
    )

    (else (set! count (+ count (char->integer(vector-ref myVector i))    ))  (set! count (- count 48))
    ); end of else

  ) ; end of cond

  (set! i (+ i 1))    ; inc "i" by 1
); end of do
) ; end do 

; if flag = 1 , then the input is in a correct form
(if (= flag 1) (set! output (appending output count)))

(if (= flag 1)
    output
    "Input error")
) ; END

【问题讨论】:

  • 在你发布的那一行之前有没有一行代码?可以加吗?

标签: string syntax scheme


【解决方案1】:

问题不在于字符串定义本身(没有奇怪的字符或类似的东西),而在于发生该定义的代码中的 place:你在一个过程,并且过程中的最后一行不能是define。尝试在定义之后返回一些东西,它应该可以正常工作。

我猜你刚刚开始编写程序,继续跟踪define 并编写其余代码。暂且在最后使用一个占位符值,这样解释器就不会抱怨了:

(define (double->sum myString)
  (define myVector 0) 
  (set! myVector (breaking myString))
  (define output "")
  'ok)

还有一个风格问题——虽然可以像这样定义和设置一个变量,但使用let 表达式来定义局部变量更为惯用。这就是我的意思:

(define (double->sum myString)
  (let ((myVector (breaking myString))
        (output ""))
    'ok))

这样,您就不必使用 set!,它会改变变量并违背 Scheme 中首选的函数式编程风格。

【讨论】:

  • Oscar,我下面还有很多代码...请参阅编辑后的帖子。
  • @ron 不会改变我的答案,问题仍然存在 - define 不能是过程中的最后一行。还要确保你的括号没问题,它可能就这么简单。
  • 不,最后一行代码没有定义。请查看上面的完整代码,已编辑
  • @ron 如果您正确缩进代码会有很大帮助,它很难阅读。并且请停止将右括号视为大括号,不要将它们放在单独的行中,将它们放在同一行中。你一直试图在 Scheme 中编程,就好像它是一种类 C 语言一样,这是问题的核心
  • @ron 正如@ChrisJester-Young 指出的那样,问题是因为在您的Scheme实现中所有定义必须首先出现,在您的代码中有一个set!在开头的两个定义之间,所以这就是问题所在。如果定义只引用一个过程的局部值,则将定义声明为全局变量不是一个好主意。请注意,按照我在解决方案中建议的方式使用let,这一切都不会发生。
猜你喜欢
  • 1970-01-01
  • 2020-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-12
  • 2014-02-21
  • 2021-06-16
  • 1970-01-01
相关资源
最近更新 更多