the pipe operator

the pipe operator

Learning to do it the functional way

27 Sep 2022

List.wrap, let's wrap it up

Written by: John Hidey

Recently discovered that the elixr api has a List.wrap function. This function does exactly as you might think, it wraps a term in a list. I often find myself needing to take in a single argument as an integer, a float, string, etc and wraping it in a list.

Say you have a function which has two function clauses. Lets say one takes in a string and the other takes a list and the sole purpose is to ensure the value is wrapped.

def wrap_function(string) when is_binary(string) do 
  [string]
end 

def wrap_function(list) when is_list(list) do 
  list
end

Well, that is where List.wrap will come in handy.

def improved_wrap_function(term) do 
  List.wrap(term)
end 

The way this works is simple, if you give List.wrap a term, it will return that term wrapped in a list i.e. (x -> [x]). If you give the wrap function a list, well, you get back your list unchanged and finally if you give wrap a nil, you will get back an empty list.

So next time you something wrapped, don’t forget about List.wrap.
Well, that about wrap it up. Hope this helps.