Scheme 函数返回最多第一个数字

标签 scheme

我想编写一个方案函数,它将一个列表作为其输入并返回一个列表,该列表包含输入列表中第一个数字元素之前的所有元素。

下面是一个例子:

(up-to-first-number '(a b c d 1 2 3)) ; returns (a b c d)

我怎样才能做到这一点?

最佳答案

在解释器中查找实现类似功能的现有过程。例如,在 Racket 中我们可以使用 takef - 下面简单地说明所有不是数字的元素都从列表中取出,当我们找到第一个数字时停止:

(define (up-to-first-number lst)
  (takef lst (negate number?)))

即使您使用不同的解释器,您始终可以使用 SRFI-1 的 take-while 类似的效果:
(require srfi/1) ; import the library, read your interpreter's documentation

(define (up-to-first-number lst)
  (take-while (lambda (x) (not (number? x))) lst))

作为最后的手段,您可以手动编写一个实现 - 这真的很简单,我不想破坏乐趣,所以我只会给您一些提示。用适当的表达填空:
(define (up-to-first-number lst)
  (if (or <???>   ; if either the list is empty
          <???>)  ; or the first element is a number
      <???>       ; then return the empty list
      (cons <???> ; otherwise cons the first element
            (up-to-first-number <???>)))) ; and advance the recursion

无论您选择哪种实现,都可以测试它是否按预期工作:
(up-to-first-number '(a b c d 1 2 3)) 
=> '(a b c d)

关于Scheme 函数返回最多第一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29440826/

相关文章:

macros - cadr、caddr 等的可变版本

scheme - 方案中的列表长度

lisp - 通过 SICP 工作在 Windows 下的 emacs 上运行的方案实现

c++ - Lisp 作为 C++ 应用程序中的脚本语言

lisp - 如何将相似的显示(printf)写入方案中的文件?

module - Racket /计划中的运算符重载

haskell - 为什么给 Haskell 添加宏比给 Scheme 更难

compilation - 你如何在scheme中编译一个可执行文件?

binary - Scheme 中二进制列表的乘法

lisp - Scheme 中是否有等同于 Lisp 的 "runtime"原语?