Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
734 views
in Technique[技术] by (71.8m points)

purescript - Is there better way to unwrap record from sum type?

I have a sum type with record param, records have the same prop of the same type (tag :: String), and I need to get its value from passed T type value. So I do with case pattern matching:

data T = T1 { tag :: String, ... } | T2 { tag :: String, ...} | T3 {tag :: String, ...}

fun :: T -> String
fun t = case t of
        T1 { tag } -> tag
        T2 { tag } -> tag
        T3 { tag } -> tag         

I wonder if there is a more simple, less verbose way to do this?

question from:https://stackoverflow.com/questions/65837553/is-there-better-way-to-unwrap-record-from-sum-type

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If all your cases always have this field, and its semantics is the same in all cases (otherwise why would you have a function that conflates them?), then a cleaner design would be to bring it out of the cases:

type T = { tag :: String, theCase :: TCase }
data TCase = T1 { ... } | T2 { ... } | T3 { ... }

fun :: T -> String
fun = _.tag

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...