Elixir中的切片


Learn X By Example · Elixir 篇 · Slices in Elixir


这应该是作者把《Go代码示例》中的“切片”章节复制过来改的,要知道 Elixir 是没有切片类型的。

在Elixir中,我们使用列表和元组,而不是切片。列表更加灵活,而且有和Go中切片类似的用法。

defmodule SlicesExample do
  def run do
    # Unlike Go's slices, Elixir lists are always initialized.
    # An empty list is represented as [].
    s = []
    IO.puts("uninit: #{inspect(s)} #{s == []} #{length(s) == 0}")

    # To create a list with a specific length, we can use List.duplicate/2
    s = List.duplicate(nil, 3)
    IO.puts("emp: #{inspect(s)} len: #{length(s)}")

    # We can set and get elements using list manipulation functions
    s = ["a", "b", "c"]
    IO.puts("set: #{inspect(s)}")
    IO.puts("get: #{Enum.at(s, 2)}")

    # length/1 returns the length of the list
    IO.puts("len: #{length(s)}")

    # We can append to lists using the ++ operator
    s = s ++ ["d"]
    s = s ++ ["e", "f"]
    IO.puts("apd: #{inspect(s)}")

    # Lists can be copied using the = operator
    c = s
    IO.puts("cpy: #{inspect(c)}")

    # Slicing in Elixir is done with Enum.slice/3
    l = Enum.slice(s, 2..4)
    IO.puts("sl1: #{inspect(l)}")

    # Slicing up to an index
    l = Enum.slice(s, 0..4)
    IO.puts("sl2: #{inspect(l)}")

    # Slicing from an index to the end
    l = Enum.slice(s, 2..-1)
    IO.puts("sl3: #{inspect(l)}")

    # We can declare and initialize a list in a single line
    t = ["g", "h", "i"]
    IO.puts("dcl: #{inspect(t)}")

    # Comparing lists
    t2 = ["g", "h", "i"]
    if t == t2 do
      IO.puts("t == t2")
    end

    # Creating a list of lists (similar to 2D slices in Go)
    two_d = for i <- 0..2 do
      for j <- 0..(i) do
        i + j
      end
    end
    IO.puts("2d: #{inspect(two_d)}")
  end
end

SlicesExample.run()

上面的Elixir代码使用列表和列表操作函数展示了与Go切片类似的概念。下面是一些异同点:

  1. Elixir 使用列表而不是切片。Elixir中的列表总是初始化的。
  2. 我们使用 List.duplicate/2 来创建指定长度的列表,类似于 Go 的 make
  3. 向列表添加元素使用 ++ 操作符,而不是 append
  4. Elixir中复制列表很容易,可以直接使用= (这样理解是不对的,列表是不可变的,即使更新了列表,相同元素也是共用的)
  5. Elixir中切片使用 Enum.slice/3,语法与 Go 类似。
  6. Elixir 中列表使用 == 比较,类似Go中的 slices.Equal
  7. Elixir 可以直接创建多维列表,比Go简单。

运行是个程序会看到与 Go 示例相似的输出,展示了Elixir中的列表操作。

尽管Elixir的列表和Go的切片有着相似的目标,但是它们底层是不同的。Elixir的列表是真列表,Go的切片是数组。

$ elixir slices_example.exs
uninit: [] true true
emp: [nil, nil, nil] len: 3
set: ["a", "b", "c"]
get: c
len: 3
apd: ["a", "b", "c", "d", "e", "f"]
cpy: ["a", "b", "c", "d", "e", "f"]
sl1: ["c", "d", "e"]
sl2: ["a", "b", "c", "d", "e"]
sl3: ["c", "d", "e", "f"]
dcl: ["g", "h", "i"]
t == t2
2d: [[0], [1, 2], [2, 3, 4]]

该示例展示了如何在 Elixir 中以 Go 的方式使用列表,下一站:map。

为什么要以Go的方式使用??


作者应该是个 gopher,鉴定完毕!但个人还是不建议用这种方式去理解 Elixir。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值