0

I'm in a situation where I use a tuple defined as type synonym, so I can't really use record structure. Is there a way to get these elements?

To be more specific here is what I mean:

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

 type Title = String

 type SalesPrice = Int   

 etc

How can I get only Title and ReleaseDate for an example. Besides than defining a getter function for every position in the tuple of course.

eightShirt
  • 1,457
  • 2
  • 15
  • 29
ayan ahmedov
  • 391
  • 1
  • 5
  • 23

3 Answers3

7

One other option is to import the package 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

I wouldn't recommend that you do this though. Use record syntax instead.

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

Now you can do

>>> let movie = Movie "The Terminator" "James Cameron"
                      ["Arnold Schwartzenegger", " Michael Biehn"]
                      1984 "Science Fiction" 19.99
>>> title movie
"The Terminator"
>>> releaseDate movie
1984
Chris Taylor
  • 46,912
  • 15
  • 110
  • 154
4

You need to define (or derive) a getter for every component of the tuple.

E.g.

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

Such accessors can be made simpler by using records instead.

Don Stewart
  • 137,316
  • 36
  • 365
  • 468
2

You can use uniplate to get all tuple elements of a specific type using uniplate. Note that uniplate will treat different type synonyms as if they are the same.

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

If you want something that differentiates between fields, it might be better to use record syntax: Haskell record syntax

Community
  • 1
  • 1
tohava
  • 5,344
  • 1
  • 25
  • 47