简体   繁体   中英

Creating a list of type instances in Haskell

I'm learning haskell and want to create a list to hold this (enumerator?) data. I'm not sure if you can do that or if it's best to create separate instances of the custom type. The first one is me just getting it to work. and the second version is an example of how I want to hold it. I can't imagine I could access the data easily like this, though; what do you guys suggest that I do?

Declaring a data type for holding several pieces of info about a location and trying to create a list of these types:

Here's how I'm doing it now:

data Place = Place {location :: String, degreesNorth :: Float, degreesEast:: Float, rainFall :: [Int]} deriving (Show)
london = Place {location="London", degreesNorth=51.5, degreesEast=(-0.1), rainFall=[0, 0, 3, 5, 8, 3, 0]}
cardiff = Place {location="cardiff", degreesNorth=12.5, degreesEast=(-4.1), rainFall=[90, 123, 3, 5, 8, 3, 0]}

First of all, you can not define two constants testData in your file. So you can for example define one as testDatum , and the other as testData .

Second the data constructor Place does not accept a list, you should call it on the parameters, and wrap the Place (or multiple places) in a list, so:

 :: Place
testDatum = Place "London" 51.5 (-0.1) [0, 0, 5, 8, 8, 0, 0]

testData :: [Place]
testData = [
     "London" 51.5 (-0.1) [0, 0, 5, 8, 8, 0, 0]
  ,  "Cardiff" 51.5 (-0.4) [0, 0, 3, 4, 6, 2, 0]
  ]

As @RobinZigmond says you also better use a record type here, to name the parameters:

data Place = Place
   location :: String
  , latitude :: Float
  , longitude :: Float
  , rainfall :: [Int]
  

This will automatically generate getters like location:: Place -> String , and make it more convenient to update one field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM