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?
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!
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.
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.
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.
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))
}
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