在Common Lisp中将拼写错误的文本转换为整数?

时间:2017-04-06 18:08:59

标签: lisp common-lisp

我对Common Lisp和Lisp一般都是新手。我有一个使用Common Lisp编写的任务,甚至无法弄清楚如何开始。我的程序将采用字符串格式从1到9的数字,它们将有一个拼写错误,但长度正确;例如:

too -> 2
threa -> 3

等等。在给出错误的文本时我需要打印整数,我真的不知道如何开始。任何帮助将不胜感激。

提前致谢。

1 个答案:

答案 0 :(得分:2)

听起来很有趣: - )

让我们以通常的Lisp方式来做 - 通过成长语言来解决问题。

问题是:将字符串与字典匹配,以便最多允许一个拼写错误。

这是字典:

(defparameter *dictionary*
  (loop for i from 1 to 9 collect (cons (format nil "~R" i) i)))

两个字符串匹配意味着什么?

(defun diff (s1 s2)
  "Count the number of differences in the shortest common start."
  (loop for c1 across s1
    for c2 across s2
    sum (if (char= c1 c2) 0 1)))
(diff "abc" "abcde")
==> 0
(diff "abc" "aba")
==> 1

现在匹配:

(defun matchp (s1 s2)
  "Two strings match iff they have the same length and 1 different character."
  (and (= (length s1)
          (length s2))
       (= 1 (diff s1 s2))))
(matchp "a" "b")
==> T
(matchp "too" "two")
==> T
(matchp "one" "one")
==> NIL

最后,在字典中找到字符串:

(defun parse-string (s)
  (loop for (name . number) in *dictionary*
    if (matchp name s) return number))
(parse-string "one")
==> NIL  ; not found
(parse-string "onn")
==> 1
(parse-string "too")
==> 2
(parse-string "thre3")
==> 3
(parse-string "foor")
==> 4
(parse-string "fivv")
==> 5
(parse-string "sis")
==> 6
(parse-string "sever")
==> 7
(parse-string "aight")
==> 8
(parse-string "nane")
==> 9

PS。我故意使用相当先进的loop工具:如果这是作业,你可能不允许使用它,所以你必须使用更简单的习语重写我的代码。

PPS。您应该阅读一本书,aclpcl都很好。