kwfuns v0.0.4 Kwfuns

Kwfuns allows to specify keyword list arguments with default values.

It exposes the macros defkw and defkwp to define a function with keyword list arguments available in the body of the function exactly the same as positional parameters.

While the former defines a public function the later defines a private one.

defkw say_hello(to, greeting: "Hello") do
  IO.puts( "#{greeting}, #{to}" )
end

If values are required that can be specified with the likewise exposed kw_required function

defkw say_hello(to: kw_required, greeting: "Hello") do
  IO.puts( "#{greeting}, #{to}" )
end

Caveat:

For the time being defkw and defkwp do not support positional arguments with defaults. If you try you will get a rather cryptic error message. Implemenation of this feature is scheduled for version 0.1

Summary

Functions

A placeholder to designate required keywords. It is made available to the module using Kwfuns

Macros

Define a function with defaulted keyword parameters that are syntactically available in the same way as positional parameters

Same semantics as defkw but a private function is defined

Functions

kw_required()

A placeholder to designate required keywords. It is made available to the module using Kwfuns

Macros

defkw(arg, list)

Define a function with defaulted keyword parameters that are syntactically available in the same way as positional parameters.

Here is a simple example:

defkw multiply_sum( factor, lhs: 0, rhs: 1 ) do
  factor * ( lhs + rhs )
end

would correspond to the following code

def multiply_sum( factor, keywords // [] ) do
  %{lhs: lhs, rhs: rhs} =
    Keyword.merge( [lhs: 0, rhs: 0], keywords ) 
    |> Enum.into( %{} )
  factor * ( lhs + rhs )
end

However if required keywords are specified as follows:

defkw multiply_sum( factor: kw_required, lhs: 0, rhs: 0 ) do
  factor * ( lhs + rhs )
end

The corresponding code is a little bit more complex

def multiply_sum( keywords // [] ) do
  missing_keywords = [:factor] -- Keyword.keys( keywords )
  unless Enum.empty?(missing_keywords) do
    raise ArgumentError, message: "The following required keywords have not been provided: factor" 
  end
  %{factor: factor, lhs: lhs, rhs: rhs} =
    Keyword.merge( [lhs: 0, rhs: 0], keywords ) 
    |> Enum.into( %{} )
  factor * ( lhs + rhs )
end
defkwp(arg, list)

Same semantics as defkw but a private function is defined.