Guest User

Untitled

a guest
Jan 15th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.90 KB | None | 0 0
  1. package tutorial
  2.  
  3. trait Sequence[T] {
  4.   def size: Int
  5.   def slice(from: Int, to: Int): T
  6.   def description: String = "Sequence"
  7. }
  8.  
  9. trait HasCodons {
  10.   def codons: Iterator[String]
  11. }
  12.  
  13. trait NTSequence[T] extends Sequence[T] {
  14.   def bp(position: Int): Char = data(position)
  15.   def data: String
  16.   def size = data.size
  17.   override def toString = data
  18.   override def description = "NTSequence"
  19. }
  20.  
  21. case class RNA(data: String) extends NTSequence[RNA] with HasCodons {
  22.   override def description = "RNA"
  23.   def translate = PP(this)
  24.   def slice(from: Int, to: Int) = RNA(data.slice(from, to))
  25.   def codons = data.grouped(3)
  26. }
  27.  
  28. case class DNA(data: String) extends NTSequence[DNA] {
  29.   override def description = "DNA"
  30.   def transcribe: RNA = RNA(complement.data.replace("T", "U"))  
  31.   def slice(from: Int, to: Int) = DNA(data.slice(from, to))
  32.  
  33.   def complement = DNA(data.map(_ match {
  34.     case 'A' => 'T'
  35.     case 'C' => 'G'
  36.     case 'G' => 'C'
  37.     case 'T' => 'A'
  38.     case _   => throw new Exception("Unexpected character in DNA")
  39.   }))
  40. }
  41.  
  42. case class PP(rna: RNA) extends Sequence[PP] {
  43.   def size = rna.size / 3
  44.   override def description = "Polypeptide/protein"
  45.   def slice(from: Int, to: Int) = PP(rna.slice(from * 3, to * 3))
  46.   override def toString = Helper.toAAString(rna)
  47. }
  48.  
  49. object Helper {
  50.  
  51.   def describe(s: Sequence[_]): String = {
  52.     s match {
  53.       case RNA("UAA")     => "Stop codon RNA"
  54.       case RNA(_)         => "RNA"
  55.       case DNA(_)         => "DNA"
  56.       case PP(_) => "Polypeptide/protein"
  57.       case _              => "Unknown sequence"
  58.     }
  59.   }
  60.  
  61.   val codonAminoMap = Map("GCA" -> 'A', "AGA" -> 'R', "GAC" -> 'D',
  62.     "AAC" -> 'N', "UGC" -> 'C')
  63.   val aminoCodonMap = codonAminoMap.map(_.swap)
  64.  
  65.   def toAA(codon: String) = codonAminoMap(codon)
  66.   def toCodon(aa: Char) = aminoCodonMap(aa)
  67.  
  68.   def toAAString(hc: HasCodons) = hc.codons.map(toAA(_)).mkString
  69.  
  70. }
Add Comment
Please, Sign In to add comment