代码之家  ›  专栏  ›  技术社区  ›  Bercovici Adrian

在ADT上解析readeither

  •  1
  • Bercovici Adrian  · 技术社区  · 6 年前

    你好我想知道 Algebraic Data Type 如何解决以下问题:

    u::Text->String
    u =Data.Text.unpack
    
     data Numeric=I Int | D Double
    
     readNumeric::Text->Either String Numeric
     readNumeric text=let str=u text in
                          if '.' `elem` str then 
                           D (readEither str::Either String Double)
                          else
                           I (readEither str::Either String Int)
    

    我怎么能把这两个都盖上 sides 属于 Either 给定一个 ADT ?实际 2*2 案例,统一?

    我在考虑使用 fromRight 在每个分支上(例如 fromRight (D 0) )的 pattern-matching (在我们的情况下,如果只有2个案例),但我不知道是不是 最好的方法。 但是 从右边 返回内部类型..我要保留 要么

    有什么想法吗?

    1 回复  |  直到 6 年前
        1
  •  2
  •   talex    6 年前

    这不是你需要的吗?

    readNumeric::Text -> Either String Numeric
    readNumeric text=let str = u text in
                          if '.' `elem` str then 
                           fmap D (readEither str::Either String Double)
                          else
                           fmap I (readEither str::Either String Int)