Early exit

How can I do a early exit in Elixir? Is it possible?

I’ve have this coffee script code and I’m trying to translate to Elixir.

isWordEnd = (pos, subject, subject_lw, len) ->
  return true if  pos is len - 1 

  return verifyWordEndOrSeparator(pos,subject,subject_lw) 

end

In the first moment I’ve tried to create a pattern matching like that…

def isWordEnd? (len -1 , subject, subject_lw, len), do: true
def isWordEnd?(pos, subject, subject_lw, _) do
       verifyWordEndOrSeparator(pos,subject, subject_lw)
end

but I got some errors so I think is not possible, I’ve tried guard clasules with no luck either. In the end I’ve came up with something like this


  def isWordEnd?(pos, subject, subject_lw, len) do
  
    if  pos == len - 1 do
        return true 
    end

    verifyWordEndOrSeparator(pos,subject, subject_lw)
  end 

Is it possible to early return or I need to change my code structure to a if/else block?

There is no return in Elixir AFAIK.

I think you were going down the right path with multple function clauses. Guard clauses are where you can put an expression match on a function (Guard Clause Tutorial)

Something like

def isWordEnd( pos, subject, subject_lw, len ) when pos == len - 1 do
   #do stuff

end

I’m not sure if you can do math in the when clause but it’s an avenue to check

Otherwise, you just use an if statement like

def isWordEnd?(pos, subject, subject_lw, len) do
  if  pos == len - 1 do
       true 
  else
      verifyWordEndOrSeparator(pos,subject, subject_lw)
   end
end
2 Likes

You can do simple math yes.

3 Likes