I am new to Scala and functional programming in general. So here's my doubt.
In a function with pattern matching, when case Nil
is matched, and we want to return Nil
, should we return Nil
or the data type itself? For example,
def drop[A](l: List[A], n: Int): List[A] = {
if (n <= 0) l
else l match {
case Nil => Nil
case Cons(_, t) => drop(t, n - 1)
}
}
This is a function which drops the first n
head elements from a Singly Linked List. Here, for the first case, should I return Nil
(maybe as a good practice) or should I return l
(because it then we won't have to construct the Nil
object)?
Return Value: This method returns a Pattern which is the pattern to be matched by this Matcher. import java.util.regex.*; import java.util.regex.*;
My first experience with pattern matching was a few years ago when I was fiddling with some functional programming languages like Elixir and F#. The ability to pattern match a value or object was one thing that I was missing when I was writing code in C# (and also in JavaScript).
Luckily, the release of C# 8 extended the pattern match syntax by supporting more features, which were further enhanced in C# 9, and it also seems like this trend is continuing in the upcoming versions of C#. So why am I excited about this?
There is only one singleton instance of the Nil
object. When you write Nil
you don't create a new one every time, you just use the only one that exists.
It's typically best to write Nil
because it's more readable. At least that's what I've always read and written.
Since there is only one instance of Nil so it does not matter since it is the actual same object.
Now the real question is: what is more readable?
Nil
, then Nil
is returned, then write Nil => Nil
l
, even if it is actually Nil
, then write Nil => l
IMHO, in your case, Nil => Nil
is more clear to me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With