Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/apache-spark/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Common lisp 格式是否为列表迭代提供计数器_Common Lisp - Fatal编程技术网

Common lisp 格式是否为列表迭代提供计数器

Common lisp 格式是否为列表迭代提供计数器,common-lisp,Common Lisp,我经常想输出列表并打印它们在列表中的位置,例如 ”(abc)将变成“1:a2:b3:c” 由于FORMAT已经支持对给定列表进行迭代,我想知道它是否还提供某种计数指令 例如,格式字符串可以如下所示:“~{@C:~a~}”,而~@C将是计数器。生成编号列表的一种不太简单但可重复使用的方法是使用带有用户定义函数的~//code>指令()。例如: (let ((position 0)) (defun init-pos(str arg col at) (declare (ignore str

我经常想输出列表并打印它们在列表中的位置,例如

”(abc)
将变成
“1:a2:b3:c”

由于
FORMAT
已经支持对给定列表进行迭代,我想知道它是否还提供某种计数指令


例如,
格式
字符串可以如下所示:
“~{@C:~a~}”
,而
~@C
将是计数器。

生成编号列表的一种不太简单但可重复使用的方法是使用带有用户定义函数的
~//code>指令()。例如:

(let ((position 0))
  (defun init-pos(str arg col at)
    (declare (ignore str arg col at))
    (setf position 0))
  (defun with-pos(str arg col at)
    (declare (ignore col at))
    (format str "~a:~a" (incf position) arg)))
然后写下如下格式:

(format nil "~/init-pos/~{~/with-pos/~^ ~}" nil '(a b c))
请注意,如评论中所述,此解决方案有两个限制:

  • 如果需要在并发线程中格式化对象,则不能使用它,并且
  • 不能将其用于嵌套列表

  • 如果你想要一个无聊的答案,那就来吧:

    (format T "~:{~a:~a ~}" (loop for i from 0 for e in '(x y z) collect (list i e)))
    
    现在来看一个更有趣的!与@Renzo的回答类似,它使用Tilde指令来实现其工作

    (defvar *count* 0)
    (defvar *printer* "~a")
    
    (defun iterate-counting (stream arg c at)
      (declare (ignore c))
      (let ((*count* (if at -1 0)))
        (destructuring-bind (*printer* delimiter &rest args) arg
          (format stream (format NIL "~~{~~/iterate-piece/~~^~a~~}" delimiter) args))))
    
    (defun iterate-piece (stream arg &rest dc)
      (declare (ignore dc))
      (incf *count*)
      (format stream *printer* *count* arg))
    
    这使用了两个特殊的变量来保证线程安全并允许嵌套。不过,我不会说它使用起来很方便。要列出的参数的第一项必须是表示如何打印参数和计数器的格式字符串。对于这种格式列表,第一个参数是计数器,第二个参数是要列出的实际项。如果需要使用,您可以切换这些选项。第二项应该是一个字符串,作为每个项之间的分隔符打印。最后,列表的其余部分必须是要打印的实际项目

    (format T "~/iterate-counting/" '("~a:~a" " " x y z))
      => 1:X 2:Y 3:Z
    (format T "~/iterate-counting/" '("~a:~/iterate-counting/" " " ("~a>~a" "," 0 1 2) ("~a>~a" "," a b c) ("~a>~a" "," x y z)))
      => 1:1>0,2>1,3>2 2:1>A,2>B,3>C 3:1>X,2>Y,3>Z
    
    如果希望它从零开始计数,请将
    @
    修饰符添加到
    迭代计数

    (format T "~@/iterate-counting/" '("~a:~a" " " x y z))
      => 0:X 1:Y 2:Z
    

    我个人不会使用这个,因为如果你无意中发现了这个指令,那么发生的事情就不那么明显了。对于潜在的未来读者来说,为它编写一个定制的函数可能比尝试ab/使用非线程安全的
    格式

    要容易得多。它也不适用于分层打印-列表列表。我选择了您的循环构造。它比
    ~/
    指令更易于编写和读取。