Skip to content

Instantly share code, notes, and snippets.

@ray-sh
Created August 1, 2017 14:24
Show Gist options
  • Save ray-sh/e43a638d7119189c5c4476bab6361779 to your computer and use it in GitHub Desktop.
Save ray-sh/e43a638d7119189c5c4476bab6361779 to your computer and use it in GitHub Desktop.
tuple and list
defmodule TupleAndListTest do
@moduledoc false
use ExUnit.Case
test "tuple cur" do
'''
Tuples are most appropriate to group a small,
fixed number of elements together. When you need a dynamically sized collection, you can use lists.
'''
#Bench mark for tuple and list https://aneta-bielska.github.io/blog/benchmarking-elixir-lists-and-tuples-example.html
#create
tuple = {"jack",11,"boy"}
#get Tuple的get操作比较快,o(1)
assert "jack" == elem(tuple,0)
#update,update总是有有内存前拷贝
assert put_elem(tuple,1,12) == {"jack",12,"boy"}
end
test "list curd" do
l1 = [1 |[2 |[3]]]
#query
#query is o(n) operation
'''
Enum.at is again an O(n) operation: it iterates from the beginning of the list to the desired element.
Lists are never a good fit when direct access is called for.
For those purposes, either tuples, maps, or a higher-level data structure is appropriate.
'''
assert Enum.at(l1,0) == 1
assert 1 in l1
#update will take o(n)
assert List.replace_at(l1,0,-1) == [-1,2,3]
#insert will take o(n),头插最快,没有任何内存消耗和查找,中插(前段:浅拷贝,中间插入新的内存,尾部共享)
assert List.insert_at(l1,1,4) == [1,4,2,3]
#insert at end will take n, 尾插最慢,所有前面全部浅拷贝
assert List.insert_at(l1,-1,4) ==[1,2,3,4]
#concatenate
assert [1,2] ++ [3,4] == [1,2,3,4]
#head
assert hd([1,2,3]) == 1
#tail
assert tl([1,2]) == [2]
assert tl([1]) == []
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment