progs/lecture4.scala
author Christian Urban <urbanc@in.tum.de>
Tue, 27 Nov 2018 21:41:59 +0000
changeset 218 22705d22c105
child 222 e52cc402caee
permissions -rw-r--r--
updated
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
218
22705d22c105 updated
Christian Urban <urbanc@in.tum.de>
parents:
diff changeset
     1
def distinctBy[B, C](xs: List[B], f: B => C, acc: List[C] = Nil): List[B] = xs match {
22705d22c105 updated
Christian Urban <urbanc@in.tum.de>
parents:
diff changeset
     2
  case Nil => Nil
22705d22c105 updated
Christian Urban <urbanc@in.tum.de>
parents:
diff changeset
     3
  case (x::xs) => {
22705d22c105 updated
Christian Urban <urbanc@in.tum.de>
parents:
diff changeset
     4
    val res = f(x)
22705d22c105 updated
Christian Urban <urbanc@in.tum.de>
parents:
diff changeset
     5
    if (acc.contains(res)) distinctBy(xs, f, acc)  
22705d22c105 updated
Christian Urban <urbanc@in.tum.de>
parents:
diff changeset
     6
    else x::distinctBy(xs, f, res::acc)
22705d22c105 updated
Christian Urban <urbanc@in.tum.de>
parents:
diff changeset
     7
  }
22705d22c105 updated
Christian Urban <urbanc@in.tum.de>
parents:
diff changeset
     8
} 
22705d22c105 updated
Christian Urban <urbanc@in.tum.de>
parents:
diff changeset
     9
22705d22c105 updated
Christian Urban <urbanc@in.tum.de>
parents:
diff changeset
    10
22705d22c105 updated
Christian Urban <urbanc@in.tum.de>
parents:
diff changeset
    11