Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Elixir Default Params #19

Open
byhbt opened this issue Mar 16, 2021 · 0 comments
Open

Elixir Default Params #19

byhbt opened this issue Mar 16, 2021 · 0 comments

Comments

@byhbt
Copy link
Owner

byhbt commented Mar 16, 2021

Problem:

I don't understand this code for set default function in Elixir

defmodule Sample.Default.Params do
  def first(list, val \\ nil)
  def first([head | _], _), do: head
  def first([], val), do: val
end

# defmodule Sample.Default.Params do
#   def first(list, val \\ nil), do: val # Why we remove this one?
#   def first([head | _], _), do: head
#   def first([], val), do: val
# end

# The warnning message
# warning: this clause for first/2 cannot match because a previous clause at line 2 always matches
#   sample_default_params.exs:3
# warning: this clause for first/2 cannot match because a previous clause at line 2 always matches
#   sample_default_params.exs:4

# Test cases
# Sample.Enum.first([1,2,3]) # => 1
# Sample.Enum.first([], 1) # => 1
# Sample.Enum.first([]) # => nil
# Sample.Enum.first([1,2,3], 0) # => 1

Solution:

Lesson:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant