Skip to content

Elixir Default Params #19

@byhbt

Description

@byhbt

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:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions