简体   繁体   中英

Haskell, data type function and how to extract information?

i created two data types which let me create a "Hill" and a "MountainChain":

data Hill = Hill Name Size Isolation Prominence
  deriving(Eq,Show)
type Name      = String
type Size     = Float
type Isolation  = Float
type Prominence = Float

data MountainChain = MountainChain Name [Hill]
  deriving(Eq,Show)

Example:

fstHill = Hill "fstHill" 45.0 18.0 4.0

scdHill = Hill "scdHill" 222.0 60.0 15.0

output: 

*Main> fstHill
Hill "fstHill" 45.0 18.0 4.0
*Main> scdHill
Hill "scdHill" 222.0 60.0 15.0

My question now is how to write a function that will return the maxSize of an Hill within the MountainChain and a function that returns the name of the highest Hill (within the MC) with the following types:

mSize :: MountainChain -> Size
majorHill :: MountainChain -> Name

You can implement mSize easily using pattern matching and a helper function:

maxSize' :: Hill -> (Size, Name)
maxSize' (Hill n s _ _) = (s, n)

maxSize :: MountainChain -> Size
maxSize (MountainChain _ mc) = fst $ maximum $ maxSize' <$> mc

majorHill :: MountainChain -> Name
majorHill (MountainChain _ mc) = snd $ maximum $ maxSize' <$> mc

What's happening here is that maxSize does a pattern match against the Hill type and extracts the name and size. It then takes the value of a tuple with the size as its first element (there's a reason for that, and I'll get to it in a bit).

maxSize just maps maxSize' over a MountainChain , which (thanks to pattern matching) is treated just like a list of Hill s. We then apply maximum over the returned list of [(Float, String)] . maximum is fortunately smart enough that it'll perform a stable sort on a list of tuples using the first element in each tuple. Finally, we extract the first element from the single tuple returned by maximum using fst .

majorHill once again makes use of this mechanic, but extracts the name (using snd ) instead of the height.

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