【问题标题】:How to get an element from tuple defined as type synonym in haskell如何从定义为haskell中类型同义词的元组中获取元素
【发布时间】:2013-07-29 13:04:52
【问题描述】:

我处于使用定义为类型同义词的元组的情况,所以我不能真正使用记录结构。 有没有办法获取这些元素?

更具体地说,我的意思是:

 type Movie  = (Title, Regisseur, MainActors, ReleaseDate, Genre, SalesPrice)  

 type Title = String

 type SalesPrice = Int   

 etc

例如,我怎样才能只获得TitleReleaseDate。当然,除了为元组中的每个位置定义一个 getter 函数。

【问题讨论】:

    标签: haskell tuples getter


    【解决方案1】:

    另一种选择是导入包Control.Lens

    >>> import Control.Lens
    >>> let movie = ( "The Terminator"
                    , "James Cameron"
                    , ["Arnold Schwartzenegger", "Michael Biehn"]
                    , 1984
                    ,"Science Fiction"
                    , 19.99)
    >>> movie ^. _1
    "The Terminator"
    >>> movie ^. _4
    1984
    

    不过,我不建议您这样做。请改用记录语法。

    data Movie = Movie
               { title       :: String
               , director    :: String
               , mainActors  :: [String]
               , releaseDate :: Int
               , genre       :: String
               , price       :: Double
               } deriving (Eq,Ord,Show)
    

    现在你可以做

    >>> let movie = Movie "The Terminator" "James Cameron"
                          ["Arnold Schwartzenegger", " Michael Biehn"]
                          1984 "Science Fiction" 19.99
    >>> title movie
    "The Terminator"
    >>> releaseDate movie
    1984
    

    【讨论】:

      【解决方案2】:

      您需要为元组的每个组件定义(或派生)一个 getter。

      例如

      title :: Movie -> Title
      title (t,_,_,_,_,_,_) = t
      

      这样的访问器可以通过使用记录来简化。

      【讨论】:

        【解决方案3】:

        您可以使用 uniplate 来获取特定类型的所有元组元素。请注意,uniplate 会将不同类型的同义词视为相同。

        import Data.Generics.Uniplate.Data
        .
        .
        .
        let [title] = childrenBi movie
        

        如果您想要区分字段的内容,最好使用记录语法:Haskell record syntax

        【讨论】:

        • 无论如何都是一个不错的建议。 — 记录语法绝对在这里更可取,IMO。
        猜你喜欢
        • 2018-05-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多