简体   繁体   中英

how to make a new type in julia?

I wrote a haskell code for translate RNA codon like this:

data Base = U | C | A | G
data Amino = Phe | Lue | Ile | Met | Val | Ser | Pro | Thr | Ala |
       Tyr | Stop | His | Gln | Asn | Lys | Asp | Glu | Cys | Trp | Arg | Gly deriving Show

codon :: Base -> Base -> Base -> Amino

parse :: String -> [Base]
parse = map go where
  go 'U' = U
  go 'A' = A
  go 'C' = C
  go 'G' = G

convert :: [Base] -> [Amino]
convert [] = []
convert (x1:x2:x3:xs) = codon x1 x2 x3 : convert xs
convert _ = undefined

main = do
  input <- getLine
  let x = show . convert . parse $ input
  putStrLn x

codon U U U = Phe 
codon U U C = Phe
codon U U A = Lue 
codon U U G = Lue 
codon C U U = Lue 

And i want to write julia code like that. To make a new type like Base or Amino , i found abstract type at julia document, i couldn't find how to make a new type.

How to define new type like Base and U , C , A , G ?

Here it is. I do not know neither genomics nor Haskell but you should like this code.

@enum Baze::Int8 U C A G
@enum Amino::Int8 Phe Lue Ile Met Val Ser Pro Thr Ala Tyr Stop His Gln Asn Lys Asp Glu Cys Trp Arg Gly


using Memoize
@memoize function parseS(T::Union{Type{Baze},Type{Amino}}, s::Symbol)
    dat = Dict(value => key for (key, value) in Base.Enums.namemap(T))
    T(dat[s])
end

import Base.parse
parse(T::Union{Type{Baze},Type{Amino}}, str)=parseS(T, Symbol(str))

Now let us see how it works. I am not sure whether you prefer 4-Tuple or perhaps a Dict for Codon anyway having this code changing is already easy.

julia> Codon = Tuple{Baze, Baze, Baze, Amino};

julia> codon1 = Codon(parse.(Codon.types,["U","C", "A", "Tyr"]))
(U, C, A, Tyr)

julia> codon2 = Codon(parseS.(Codon.types,[:U,:C,:A,:Tyr]))
(U, C, A, Tyr)

julia> codon3 = (U,C,A,Tyr)
(U, C, A, Tyr)

julia> codon1 === codon2 === codon3
true

Looks like mini genetics framework to me :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM