使用高阶函数映射的字符串加密

时间:2016-11-19 14:30:06

标签: scheme lisp racket higher-order-functions map-function

我写了以下字符串加密代码。但我希望能够使用(读取)而不是使用硬编码值从键盘获取加密密钥。但是我不能这样做,因为map将列表作为参数。

#lang racket

(define character-encryption
  (lambda (ch)
    (if (char-alphabetic? ch)
        (character-rotation ch 3) 
        ch))) ; non-letter will not be encrypted.

(define character-rotation
  (lambda (ch num)
    (integer->char (+ (char->integer ch) num)))) ; key=3

(define string-encryption
  (lambda (str) 
    (list->string (map character-encryption (string->list str)))))

更新

> (string-encryption (read))
"foo bar"                        ; <- entered
"irr edu"                        ; output

更新

#lang racket

(define character-encryption
  (lambda (key)
    (lambda (ch)
      (if (char-alphabetic? ch)
          (character-rotation ch key) 
          ch)))) ; non-letter will not be encrypted.

(define character-rotation
  (lambda (ch num)
    (integer->char (+ (char->integer ch) num)))) ; key=3 (I want to read this number)


(define string-encryption
  (lambda (key str) 
    (list->string (map (character-encryption key) (string->list str)))))

1 个答案:

答案 0 :(得分:1)

使用read-line读取一行。结果是一个字符串。

在这里阅读更多内容: Docs on read-line