药剂列表串联 [英] Elixir list concatenation

查看:54
本文介绍了药剂列表串联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我一直在和Elixir玩,对某些事情有些困惑:

So I've been playing with Elixir and am a bit confused about something:

iex> [ 1 | [ 2 ] ] // [ 1, 2] (expected)
iex> [ 1 | 2 ] // [ 1 | 2 ] (huh?)

我的困惑在于为什么第二个版本会执行它的工作.我知道 2 不是列表,所以它不能将"head"和"tail"连接起来,但是,我认为,当尾部不是列表时,它应该抛出一个错误.我一直在尝试考虑这种情况的用例,但是空手而归.如果有人能解释为什么这是理想的行为,我将非常感激.谢谢!

My confusion is in why the second version does what it does. I understand that 2 is not a list, so it can't concatenate the "head" with the "tail", but, in my opinion, it should throw an error when the tail is not a list. I've been trying to think of a use-case for having this behavior but have come empty-handed. If anyone can explain why this is the desired behavior, I'd really appreciate it. Thanks!

推荐答案

列表的尾部实际上可以是任何术语,而不仅仅是另一个列表.有时称为不当列表".

The tail of a list can actually be any term, not just another list. This is sometimes called an "improper list".

Erlang文档举例说明使用它来构建无限列表,但您不太可能在野外遇到它.想法是,在这种情况下,尾部不是列表,而是一个函数,该函数将返回具有下一个值和函数的另一个不正确的列表:

The Erlang documentation gives an example on how to use this to build infinite lists, but it is unlikely that you will encounter this in the wild. The idea is that the tail is in this case not a list, but a function that will return another improper list with the next value and function:

defmodule Lazy do
  def ints_from(x) do
    fn ->
      [x | ints_from(x + 1)]
    end
  end
end

iex> ints = Lazy.ints_from(1)
#Function<0.28768957/0 in Lazy.ints_from/1>

iex> current = ints.()
[1 | #Function<0.28768957/0 in Lazy.ints_from/1>]

iex> hd(current)
1

iex> current = tl(current).()
[2 | #Function<0.28768957/0 in Lazy.ints_from/1>]

iex> hd(current)
2

iex> current = tl(current).()
[3 | #Function<0.28768957/0 in Lazy.ints_from/1>]

iex> hd(current)
3

但是,我们可以使用 Stream 模块在Elixir中更轻松地实现无限流:

However, we can achieve infinite streams much more easily in Elixir using the Stream module:

iex> ints = Stream.iterate(1, &(&1+1))
#Function<32.24255661/2 in Stream.unfold/2>

iex> ints |> Enum.take(5)
[1, 2, 3, 4, 5]

不当列表的另一种(伪)用例是所谓的 chardata 值.这些功能使您可以优化需要频繁追加到字符列表(单引号字符串)的情况,因为字符列表是链接列表,因此添加起来很昂贵.通常,您也不会真正看到带有chardata的不正确列表,因为我们只能使用常规列表-但请放心,它们可以用于构建chardata.如果您想全面了解有关chardata的信息,建议您 The Pug Automatic上的这篇博客文章.

Another (pseudo) use case of improper lists is with so-called iodata or chardata values. These allow you to optimize situations where you need to frequently append to a charlist (single quoted string), due to the fact that charlists are linked lists for which appending is expensive. You normally don't really see improper lists with chardata in the wild either, because we can just use regular lists – but rest assured they could be used to build a chardata. If you want to learn more about chardata in general, I recommend this blog post from The Pug Automatic.

这篇关于药剂列表串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆