开发者

How do I compare the symbol a with the character a?

I have a list containing letters. When I do (car '(a)) it gives me the symbol a. How do I compare it to the characte开发者_如何学Pythonr a?

Must I do (eq? (car list) (car '(a))?


Symbols and characters are different kinds of data. Fortunately, Scheme is willing to let you convert nearly anything you want. In Racket, for instance:

#lang racket

;; the symbol a:
'a

;; the character a:
#\a

;; are they equal? no.
(equal? 'a #\a) ;; produces #f

;; converting a character to a symbol:
(define (char->symbol ch)
  (string->symbol (string ch)))

(char->symbol #\a) ;;=> produces 'a

;; converting a symbol to a character
(define (symbol->char sym)
  (match (string->list (symbol->string sym))
    [(list ch) ch]
    [other (error 'symbol->char 
                  "expected a one-character symbol, got: ~s" sym)])) 

(symbol->char 'a) ;; => produces #\a   

With all that said, if you're working on a homework assignment, the instructor almost certainly has an easier path in mind for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜