如何从haskell中定义为类型同义词的元组中获取元素
我使用的是定义为类型同义词的元组,所以我不能真正使用记录结构。 有没有办法获取这些元素 更具体地说,我的意思是:如何从haskell中定义为类型同义词的元组中获取元素,haskell,tuples,getter,Haskell,Tuples,Getter,我使用的是定义为类型同义词的元组,所以我不能真正使用记录结构。 有没有办法获取这些元素 更具体地说,我的意思是: type Movie = (Title, Regisseur, MainActors, ReleaseDate, Genre, SalesPrice) type Title = String type SalesPrice = Int etc 例如,如何仅获取标题和发布日期。当然,除了为元组中的每个位置定义一个getter函数之外。您还需要为元组的每个组件
type Movie = (Title, Regisseur, MainActors, ReleaseDate, Genre, SalesPrice)
type Title = String
type SalesPrice = Int
etc
例如,如何仅获取标题
和发布日期
。当然,除了为元组中的每个位置定义一个getter函数之外。您还需要为元组的每个组件定义(或派生)一个getter
例如
这样的访问器可以通过使用记录来简化。您可以使用uniplate来使用uniplate获取特定类型的所有元组元素。请注意,uniplate会将不同类型的同义词视为相同的同义词
import Data.Generics.Uniplate.Data
.
.
.
let [title] = childrenBi movie
如果您想要区分字段,最好使用记录语法:另一个选项是导入包
控件.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
无论如何,这是一个很好的建议在这里,记录语法绝对更可取,IMO。
>>> let movie = Movie "The Terminator" "James Cameron"
["Arnold Schwartzenegger", " Michael Biehn"]
1984 "Science Fiction" 19.99
>>> title movie
"The Terminator"
>>> releaseDate movie
1984