LISP 仅在特定情况下从列表中提取元素

标签 lisp common-lisp extract

我正在寻找的函数必须返回第一个的索引,即一对“”。

例如,序列

{ " h i , a l l " : 3 , " h o w , i s " : " x " }

'( #\{ #\" #\h #\i #\, #\a #\l ... )

函数应该返回 11,而不是 4(第一次出现的逗号),因为它在“”之间。

我试过这个:

(defun control-comma (x p)
  (cond ((eql (car x) #\")
         (control-comma (subseq x (+ (position #\" x :start (+ 1 p)) 1)) p))
        ((eql (car x) #\,)
         p)
        (t
         (control-comma (cdr x) (+ 1 p)))
        )
  )

使用 x 作为输入列表和 p 作为 0 参数来计算位置,但它不起作用并且似乎与我正在寻找的解决方案相去甚远。

谢谢你的每一个建议。

最佳答案

我建议您使用预定义的 position-if,而不是定义一个复杂的函数。运算符(operator):

(defun first-comma (string start)
   (let ((in-double-quote nil))
     (position-if 
       (lambda (x)
         (case x
           ((#\") (progn (setf in-double-quote (not in-double-quote)) nil))
           ((#\,) (not in-double-quote))))
      string
      :start start)))

CL-USER> (first-comma (coerce "{ \"hi, all\" : 3, \"how, is\" : \"x\" }" 'list) 0)
15

一个更复杂的递归解决方案再次基于一次扫描输入列表一个字符的想法,由以下函数给出,其中状态“双引号内”通过几个递归局部函数编码:

(defun fist-comma (x pos)
  (labels ((looking-for-comma (x pos)
             (cond ((null x) nil)
                   ((eql (car x) #\,) pos)
                   ((eql (car x) #\") (looking-for-double-quote (cdr x) (1+ pos)))
                   (t (looking-for-comma (cdr x) (1+ pos)))))
           (looking-for-double-quote (x pos)
             (cond ((null x) nil)
                   ((eql (car x) #\") (looking-for-comma (cdr x) (1+ pos)))
                   (t (looking-for-double-quote (cdr x) (1+ pos))))))
    (looking-for-comma (nthcdr pos x) pos)))

最后,请注意,在上述两个函数中,应考虑使用适当方法转义双引号的可能性。

关于LISP 仅在特定情况下从列表中提取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48218639/

相关文章:

lisp:捕获标准输出和标准错误,将其存储在单独的变量中

macros - 如何在 lisp 中用 if 形式定义递归 cond 宏?

Mysql只提取字母字符

lisp - "Overloading"具有不同参数列表的 CLOS 多方法

iOS:如何从 CGContextRef 检索图像尺寸 X、Y

JavaScript 提取器 : extract functions/objects that are really used in a web page from a library

clojure - 定义简化的 arity 偏函数

com - 是否有开源的 Common Lisp COM 包装器?

lisp - 为什么要进行功能/宏二分法?

common-lisp - 使用 ASDF 加载可选组件