Anonymous function arity error with is_string and is_integer

I am a beginner trying to make an anonymous function that takes two parameters. It needs to use guards to check if the two values are both strings or integers. If they both are strings, those strings need to be combined and printed. If they are both integers, they need to be added together and printed.

However, I am getting an error with different arities when using two is_bitstring and is_integer. Is the code below even possible using one anonymous function?

f = fn 

    x, y when is_bitstring(x) and is_bitstring(y) -> IO.puts x <> y

    x, y when is_integer(x) and is_integer(y) -> IO.puts x + y

    _ -> IO.puts "Both parameters are not strings"

end

Thank you!

The clause _ -> IO.puts "Both parameters are not strings" is only matching on a single parameter when two are expected. Therefore more likely you should be using _, _ -> IO.puts "Both parameters are not strings".

BTW, if you are checking for strings, as in bytes, then is_binary/1 is the better guard to use. It won’t guarantee the parameter is a valid UTF8 string, but it will check that it is a a group of bytes. A bitstring is any number of bits.

4 Likes