Sha256: f420eae9409b3a0b6c1fc55eeaeb07b86a4070151733233abd5cf362449f5eca

Contents?: true

Size: 1023 Bytes

Versions: 352

Compression:

Stored size: 1023 Bytes

Contents

import DNA._

class DNA(dna: String) {

  def count(char: Char): OrError[Int] =
    for {
      nucleotide <- toNucleotide(char)
      counts <- nucleotideCounts
    } yield counts(nucleotide)

  lazy val nucleotideCounts: OrError[NucleotideCounts] = {
    val zeroCounts: Either[String, NucleotideCounts] =
      Right(EmptyNucleotideCounts)

    dna.foldLeft(zeroCounts) { case (nucleotideCounts, char) =>
      for {
        nucleotide <- toNucleotide(char)
        counts <- nucleotideCounts
      } yield counts updated (nucleotide, counts.getOrElse(nucleotide, 0) + 1)
    }
  }

  private def toNucleotide(char: Char): OrError[Nucleotide] =
    if (DnaNucleotides.contains(char)) Right(char)
    else Left(s"invalid nucleotide '$char'")
}

object DNA {
  type Nucleotide = Char
  type NucleotideCounts = Map[Nucleotide,Int]
  type OrError[T] = Either[String, T]

  val DnaNucleotides: Set[Nucleotide] = Set('A', 'T', 'C', 'G')

  val EmptyNucleotideCounts: NucleotideCounts =
    DnaNucleotides map (_ -> 0) toMap
}

Version data entries

352 entries across 352 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/scala/exercises/nucleotide-count/example.scala
trackler-2.2.1.179 tracks/scala/exercises/nucleotide-count/example.scala
trackler-2.2.1.178 tracks/scala/exercises/nucleotide-count/example.scala
trackler-2.2.1.177 tracks/scala/exercises/nucleotide-count/example.scala
trackler-2.2.1.176 tracks/scala/exercises/nucleotide-count/example.scala
trackler-2.2.1.175 tracks/scala/exercises/nucleotide-count/example.scala
trackler-2.2.1.174 tracks/scala/exercises/nucleotide-count/example.scala
trackler-2.2.1.173 tracks/scala/exercises/nucleotide-count/example.scala
trackler-2.2.1.172 tracks/scala/exercises/nucleotide-count/example.scala
trackler-2.2.1.171 tracks/scala/exercises/nucleotide-count/example.scala
trackler-2.2.1.170 tracks/scala/exercises/nucleotide-count/example.scala
trackler-2.2.1.169 tracks/scala/exercises/nucleotide-count/example.scala
trackler-2.2.1.167 tracks/scala/exercises/nucleotide-count/example.scala
trackler-2.2.1.166 tracks/scala/exercises/nucleotide-count/example.scala
trackler-2.2.1.165 tracks/scala/exercises/nucleotide-count/example.scala
trackler-2.2.1.164 tracks/scala/exercises/nucleotide-count/example.scala
trackler-2.2.1.163 tracks/scala/exercises/nucleotide-count/example.scala
trackler-2.2.1.162 tracks/scala/exercises/nucleotide-count/example.scala
trackler-2.2.1.161 tracks/scala/exercises/nucleotide-count/example.scala
trackler-2.2.1.160 tracks/scala/exercises/nucleotide-count/example.scala