版本: 1.2.2,错误:
List.flatten ([a,b])将返回(a,b)。然而,在某些情况下,这并不能正常工作。例如,当(11,12,13)被期望时,List.flatten ([11,[12,13]])返回'\v\f\r‘。甚至List.flatten(10)返回'\n‘。
为什么会发生这种情况,如果有的话,解决办法是什么?
发布于 2016-07-21 09:19:16
正如greggreg解释的那样,最终列表( 11,12,13 )看起来像'\v\f\r‘,因为它包含所有可打印的acsii代码点。因此,输出是一个字符列表。
如果您需要从这个列表中获取数字,而不是字符,那么您可以这样做:
iex> sample_list = [11,12,13]
iex> [first | rest] = sample_list
iex> [second | rest] = rest
iex> [third | rest] = rest
iex> first
iex> 11
iex> second
iex> 12
iex> third
iex> 13所以,基本上,当你从一个列表中取出一个数字时,它被转换成整数。现在,由于它不是一个列表,所以它不能转换为charlist。
发布于 2016-07-19 15:29:47
如果您的列表包含所有可以表示ASCII集中可打印的UTF-8码点的整数,它将作为字符列表输出到终端。
iex> [104,101,108,108,111]
'hello'但它仍然是一个清单:
iex> 'hello' ++ ' there'
'hello there'如果它包含任何不可打印的代码点,它将作为标准列表输出:
iex> 'hello' ++ [0]
[104, 101, 108, 108, 111, 0]通过使用?运算符,您可以看到字符具有什么代码点:
iex> ?h
104我们可以在iex中使用i助手获得有关术语的信息:
iex> i 'hello'
Term
'hello'
Data type
List
Description
This is a list of integers that is printed as a sequence of characters
delimited by single quotes because all the integers in it represent valid
ASCII characters. Conventionally, such lists of integers are referred to
as "charlists" (more precisely, a charlist is a list of Unicode codepoints,
and ASCII is a subset of Unicode).
Raw representation
[104, 101, 108, 108, 111]
Reference modules
List为什么药剂会这么做?二郎。
发布于 2016-07-19 12:13:18
实际上,它与List.flatten没有关系,因为它工作得很好。这只是将可打印字符打印为ASCII字符的问题。与许多编程语言相反的是,长生不老药将字符列表视为整数列表。
例如:
a = 'abc'
hd a # 97考虑这图层的最后一个例子。
还请记住,字符串解释是一回事,但仍然有整数列表。
hd [12, 13, 14] # 12https://stackoverflow.com/questions/38458166
复制相似问题