Skip to content

Commit

Permalink
Change return type of RNA transcription to Maybe
Browse files Browse the repository at this point in the history
- Error case is now defined, eliminating the desire to throw an `error`
for invalid input.
- The test and example solution are more idiomatic to Haskell, using a
  `Maybe`.

Closes #166
  • Loading branch information
samjonester committed Jun 30, 2016
1 parent 62fc8a7 commit 3a3ce84
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 12 deletions.
6 changes: 6 additions & 0 deletions exercises/rna-transcription/DNA.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module DNA (toRNA) where

-- | if string contains invalid character, return Nothing
-- | if string contains only valid nucleotides, return Just transcription
toRNA :: String -> Maybe String
toRNA = undefined
17 changes: 10 additions & 7 deletions exercises/rna-transcription/example.hs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
module DNA (toRNA) where

toRNA :: String -> String
toRNA = map $ \c -> case c of
'C' -> 'G'
'G' -> 'C'
'A' -> 'U'
'T' -> 'A'
_ -> error $ "Invalid DNA-base: " ++ show c
import qualified Data.Map.Strict as Map

toRNA :: String -> Maybe String
toRNA = mapM (`Map.lookup` rna)
where
rna = Map.fromList [ ('C', 'G')
, ('G', 'C')
, ('A', 'U')
, ('T', 'A') ]

16 changes: 11 additions & 5 deletions exercises/rna-transcription/rna-transcription_test.hs
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,21 @@ testCase label assertion = TestLabel label (TestCase assertion)
toRNATests :: [Test]
toRNATests =
[ testCase "transcribes cytosine to guanine" $
"G" @=? toRNA "C"
Just "G" @=? toRNA "C"
, testCase "transcribes guanine to cytosine" $
"C" @=? toRNA "G"
Just "C" @=? toRNA "G"
, testCase "transcribes adenine to uracil" $
"U" @=? toRNA "A"
Just "U" @=? toRNA "A"
, testCase "transcribes thymine to adenine" $
"A" @=? toRNA "T"
Just "A" @=? toRNA "T"
, testCase "transcribes all ACGT to UGCA" $
"UGCACCAGAAUU" @=? toRNA "ACGTGGTCTTAA"
Just "UGCACCAGAAUU" @=? toRNA "ACGTGGTCTTAA"
, testCase "transcribes RNA only nucleotide uracil to Nothing" $
Nothing @=? toRNA "U"
, testCase "transcribes completely invalid DNA to Nothing" $
Nothing @=? toRNA "XXX"
, testCase "transcribes RNA only nucleotide uracil to Nothing" $
Nothing @=? toRNA "ACGTXXXCTTAA"
]

main :: IO ()
Expand Down

0 comments on commit 3a3ce84

Please sign in to comment.