99 Scala Problems 11 - Modified run-length encoding

The problem

P11 (*) Modified run-length encoding. Modify the result of problem P10 in such a way that if an element has no duplicates it is simply copied into the result list. Only elements with duplicates are transferred as (N, E) terms.

Example:

scala> encodeModified(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, ... more
                        
                

99 Scala Problems 10 - Run-length encoding of a list.

The problem

P10 (*) Run-length encoding of a list. Use the result of problem P09 to implement the so-called run-length encoding data compression method. Consecutive duplicates of elements are encoded as tuples (N, E) where N is the number of duplicates of the element E.

Example:

scala> encode(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, ... more
                        
                

99 Scala Problems Index

I decided to learn Scala. I looked for some good exercises for Scala programmers and found S-99: Ninety-Nine Scala Problems, and since writing about things helps me learning them I am going to write a post for each problem I manage to solve.

The official site provides solutions for the problems, so my solutions will obviously be influenced by those, when not the same.

CAVEAT: I am a beginner so what I state in the following posts may be inaccurate and sometimes wrong. Please submit an issue on the blog GitHub issues page.

This is the index of the problems I already discussed. I kept the original title and difficulty ranking (asterisks)