Home > database >  How to filter and are using a function in haskell
How to filter and are using a function in haskell

Time:08-02

I have a function

f::String -> String
f (a:arr) = fa a : f arr
  where
    fa :: Char -> Char
    fa 'A' = 'T'
    fa 'T' = 'A'
    fa 'G' = 'C'
    fa 'C' = 'G'

The function will not work for some input, and the error is "Non-exhaustive patterns in function f."

So I want to filter an array of strings of all the elements that work with this function.

Like:

map f arr

So it will return only the list of elements that worked out with the function.

CodePudding user response:

You can work with mapMaybe :: (a -> Maybe b) -> [a] -> [b] where f returns a Just x in case it has to perform the mapping, and Nothing if the input is invalid:

import Data.Maybe(mapMaybe)

mapRNA :: String -> String
mapRNA = mapMaybe fa
  where fa 'A' = Just 'T'
        fa 'T' = Just 'A'
        fa 'G' = Just 'C'
        fa 'C' = Just 'G'
        fa _ = Nothing

CodePudding user response:

String is a bad choice for representing a sequence of bases in the first place, as there are many, many more Char values than there are valid bases. Start with something like data Base = A | T | G | C deriving Show; then

f :: [Base] -> [Base]
f = map g
   where g :: Base -> Base
         g A = T
         g T = A
         g G = C
         g C = G

If you need to, you can write a function of type [Base] -> String that takes advantage of the Show instance derived for Base.

  • Related