I’m trying to create a closure that takes in a html tag such as “p” or “h1” and returns an anonymous function that can take a string (to go between the tags) and an optional string of tag attributes such as “style=“color: green;””.
I have tried to do this with an optional parameter and see that this can’t be done and I have also tried clauses with different arities and see this can’t also be done.
Here is my effort with an optional parameter:
defmodule Wrapper do
def html(tag) do
fn
(str, attr \\ "" ) -> "<#{tag} #{attr}>" <> str <> "<#{tag}>"
end
end
end
And here is my effort with two arities in the anonymous function
defmodule Wrapper do
def html(tag) do
fn
(str, attr) -> "<#{tag} #{attr}>" <> str <> "<#{tag}>"
(str) -> "<#{tag}>" <> str <> "<#{tag}>"
end
end
end
And used like:
h1 = Wrapper.html("h1" )
h1.("I'm a green h1 title", "style=\"color: green;\"") |> IO.puts
h1.("I'm a title") |> IO.puts
Is there another way of doing what I need here? I don’t actually need this other than learning.
–
Edited: spelling