When I get away from programming for a little while I often write some example code to get my brain warmed up again. So last night I was reading the Real World Haskell book and came across this myDrop
example, which is an implementation of a Haskell drop
function:
myDrop n xs = if n <= 0 || null xs then xs else myDrop (n - 1) (tail xs)
After reading about it, I decided to write a Scala version of myDrop
:
def myDrop(n: Int, xs: Seq[Char]): Seq[Char] = if (n <= 0 || xs == null) { xs } else { myDrop(n - 1, xs.tail) }
That was my first attempt, where I was interested in a list/sequence of characters, but the more accurate, equivalent Scala version of the Haskell myDrop
function looks like this, where I treat the Seq
type as a generic type:
def myDrop[A](n: Int, xs: Seq[A]): Seq[A] = if (n <= 0 || xs == null) { xs } else { myDrop(n - 1, xs.tail) }
Because the Seq
is defined to contain a generic type, the Seq
can now contain any sort of type, including Char
, Int
, etc.
My complete ’myDrop’ method in Scala
If for some reason you want to fool around with this code, here’s my complete source code for a mydrop
example method written in Scala:
package mydrop object MyDrop extends App { def myDrop[A](n: Int, xs: Seq[A]): Seq[A] = if (n <= 0 || xs == null) { println("done, returning xs") xs } else { println(s"n = $n, xs = $xs") myDrop(n - 1, xs.tail) } println(myDrop(2, "foobar")) }
I included some println
statements so you can see how the method works as it recursively runs. The output for the data shown looks like this:
n = 2, xs = foobar n = 1, xs = oobar done, returning xs obar
If you wanted to see a recursion example in Scala, or otherwise wanted to see the Haskell myDrop
function ported to Scala, I hope this is helpful.