emacs-lisp中如何创建整数列表

在 Emacs Lisp 中,虽然没有直接等同于 Python 的 range 函数来生成序列,但可以利用 `number-sequence` 实现类似功能。该函数支持生成整数列表,甚至可以处理小数值,尽管精度有限。此外,它还能辅助构建其他生成序列的函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文地址:https://www.lujun9972.win/blog/2022/02/17/emacs-lisp中如何创建整数列表/index.html

emacs-lisp中提供了一堆 seq-* 函数对序列进行操作,但却缺少类似 Python 中的 range 函数那样的生成序列的函数。

在网上搜索了一下才知道 emacs-lisp 中是可以使用 number-sequence 来实现类似的功能的。

number-sequence is a compiled Lisp function in ‘subr.el’.

(number-sequence FROM &optional TO INC)

  Probably introduced at or before Emacs version 22.1.

Return a sequence of numbers from FROM to TO (both inclusive) as a list.
INC is the increment used between numbers in the sequence and defaults to 1.
So, the Nth element of the list is (+ FROM (* N INC)) where N counts from
zero.  TO is included only if there is an N for which TO = FROM + N * INC.
If TO is nil or numerically equal to FROM, return (FROM).
If INC is positive and TO is less than FROM, or INC is negative
and TO is larger than FROM, return nil.
If INC is zero and TO is neither nil nor numerically equal to
FROM, signal an error.

This function is primarily designed for integer arguments.
Nevertheless, FROM, TO and INC can be integer or float.  However,
floating point arithmetic is inexact.  For instance, depending on
the machine, it may quite well happen that
(number-sequence 0.4 0.6 0.2) returns the one element list (0.4),
whereas (number-sequence 0.4 0.8 0.2) returns a list with three
elements.  Thus, if some of the arguments are floats and one wants
to make sure that TO is included, one may have to explicitly write
TO as (+ FROM (* N INC)) or use a variable whose value was
computed with this exact expression.  Alternatively, you can,
of course, also replace TO with a slightly larger value
(or a slightly more negative value if INC is negative).

而且 number-sequence 函数还支持小数,这个就比较牛逼了。

(number-sequence 0.1 1 0.1)
0.10.20.300000000000000040.40.50.60.70000000000000010.80.91.0

当然了,小数的表示不是那个准确的。

另外,我们还可以借助它实现其他生成序列的函数,比如

(defun my/repeat (x c)
  (mapcar (lambda (_)
            c)
          (number-sequence 1 x)))

(my/repeat 5 1)
11111
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值