Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I omit this Nil Case

I am mucking around with scala implementing some common algorithms. While attempting to recreate a bubble sort I ran into this issue

Here is an implementation of an the inner loop that bubbles the value to the top:

def pass(xs:List[Int]):List[Int] = xs match { 
  case Nil => Nil 
  case x::Nil => x::Nil 
  case l::r::xs if(l>r) => r::pass(l::xs)
  case l::r::xs => l::pass(r::xs)
}

My issue is with case Nil => Nil. I understand that I need this is because I could apply Nil to this function. Is there a way to ensure that Nil can't be provided as an argument in a manner that would satisfy the compiler so I can eliminate this case?

like image 254
nsfyn55 Avatar asked Sep 30 '12 15:09

nsfyn55


People also ask

How do I get rid of nil?

When you want to remove nil elements from a Ruby array, you can use two methods: compact or compact! . They both remove nil elements, but compact! removes them permanently. In this shot, we will be talking about the compact!

How do you remove nil from an array?

Array#compact () : compact () is a Array class method which returns the array after removing all the 'nil' value elements (if any) from the array. Syntax: Array. compact() Parameter: Array to remove the 'nil' value from. Return: removes all the nil values from the array.

What is a nil object?

Well, nil is a special Ruby object used to represent an “empty” or “default” value. It's also a “falsy” value, meaning that it behaves like false when used in a conditional statement. Now: There is ONLY one nil object, with an object_id of 4 (or 8 in 64-bit Ruby), this is part of why nil is special.

How do you handle nil in Ruby?

However, in terms of how it's implemented, nil is fundamentally different than in other languages. In Ruby, nil is—you've guessed it—an object. It's the single instance of the NilClass class. Since nil in Ruby is just an object like virtually anything else, this means that handling it is not a special case.


1 Answers

List has two subtypes, Nil and ::, so :: represents a list that has at least one element.

def pass(xs: ::[Int]):List[Int] = xs match { 
  case x::Nil => x::Nil 
  case l::r::xs if(l>r) => r::pass(new ::(l,xs))
  case l::r::xs => l::pass(new ::(r, xs))
}
like image 63
Kim Stebel Avatar answered Sep 25 '22 18:09

Kim Stebel