16 Jul 2013, 02:16
Dave_gnome_head_isolated_pragsmall

Dave Thomas (339 posts)

  • Try the following in iex:

    iex> [ 'cat' | 'dog' ]
    ['cat',100,111,103]
    

    Why does iex print ‘cat’ as a string, but ‘dog’ as individual numbers?

A Possible Solution</summary>

# Because the head of the new list is actually the list [?c, ?a, ?t].
# This means the overall list consists of a list and three ASCII
# characters:
#
#   [ 'cat' | 'dog' ] = [ [ ?c, ?a, ?t ], ?d, ?o, ?g ]
#
# Because the overall list contains something other than ASCII
# characters, it is displayed as a list of values. But the first value is
# the list 'cat', which _is_ just ASCII characters.

</details>

09 Jan 2014, 21:16
Generic-user-small

Daniel Ashton (7 posts)

To make it a single-level list of six characters, you can pass it to List.flatten:

iex> List.flatten ['dog' | 'cat']
'dogcat'
03 Jan 2015, 20:10
50221_2_243512.jpg__1072x720_q85_crop_pragsmall

Jason Goldberger (2 posts)

As unit test using ExUnit (with a @moduledoc too!!)


ExUnit.start()

defmodule TestCatDog do
  @moduledoc """
   The[ head | tail ] of [ 'cat' | 'dog' ] restructed (undestructured?)
   is [[99, 97, 116], 100, 111, 103] and not the equivalent of the intuitive
   [99, 97, 116, 100, 111, 103] which is 'catdog'
  """
  use ExUnit.Case

  test "[ 'cat' | 'dog' ] is unintiutive due to a nested list" do

    #['cat'|'dog'] is not a flat list
    refute ['cat' | 'dog'] == [99, 97, 116, 100, 111, 103]

    #'catdog' is a flat list
    assert 'catdog' == [99, 97, 116, 100, 111, 103]

    #['cat'|'dog'] has a nested list
    assert ['cat' | 'dog'] == [[99, 97, 116], 100, 111, 103]
  end
  
end

  You must be logged in to comment