Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the appropriate return value when the pattern matched is Nil and we want to return Nil?

Tags:

scala

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)?

like image 619
aa8y Avatar asked Feb 24 '15 20:02

aa8y


People also ask

What is the use of return value in matcher?

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.*;

When did you get your first experience with pattern matching?

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).

Will pattern match syntax be extended in the next version of C #?

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?


2 Answers

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.

like image 194
sjrd Avatar answered Oct 14 '22 06:10

sjrd


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?

  • If you want to make it clear that when you get Nil, then Nil is returned, then write Nil => Nil
  • If it seems more logical to return l, even if it is actually Nil, then write Nil => l

IMHO, in your case, Nil => Nil is more clear to me.

like image 1
Jean Logeart Avatar answered Oct 14 '22 05:10

Jean Logeart