elixir - Cross product of charlists or characters? -
i wrote
iex(87)> cross=fn ...(87)> a, b when is_list(a) , is_list(b) -> x <- a, y <- b, do: [x,y] ...(87)> a, b when not is_list(a) , is_list(b) -> y<-b, do: [a,y] ...(87)> a, b when is_list(a) , not is_list(b) -> x<- , do: [x, b] ...(87)> end
which thing gosh it's ugly. tried simpler
cross=fn(a,b) -> x <- to_charlist(a), y <- to_charlist(b), do: [x,y] end
but produced lot of bogus results when sending in single character.
so want way wrap non-lists single element list , for
work expected char or charlists either arguments. can list.wrap/1
:
cross2 = fn as, bs -> <- list.wrap(as), b <- list.wrap(bs), do: [a, b] end
test:
cross = fn a, b when is_list(a) , is_list(b) -> x <- a, y <- b, do: [x, y] a, b when not is_list(a) , is_list(b) -> y <- b, do: [a, y] a, b when is_list(a) , not is_list(b) -> x <- , do: [x, b] end cross2 = fn as, bs -> <- list.wrap(as), b <- list.wrap(bs), do: [a, b] end io.inspect cross.('abc', 'def') io.inspect cross2.('abc', 'def') io.inspect cross.(?a, 'def') io.inspect cross2.(?a, 'def') io.inspect cross.('abc', ?d) io.inspect cross2.('abc', ?d) # implementation doesn't handle case. # io.inspect cross.(?a, ?d) io.inspect cross2.(?a, ?d)
output:
['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf'] ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf'] ['ad', 'ae', 'af'] ['ad', 'ae', 'af'] ['ad', 'bd', 'cd'] ['ad', 'bd', 'cd'] ['ad']
Comments
Post a Comment