3

对 Haskell 来说是全新的。问题 - 我有一个类型构造函数,其值构造函数由 4 个组件组成:

 TrackPoint :: TP { rpm :: Integer
               , time :: Integer
               , distance :: Float
               , speed :: Float 
               } deriving (Show)

我想在 rpm 值低于 10,000 的任何时候使用 [TrackPoint] 并让它返回时间、距离和速度。我试过使用没有运气的警卫。这位新手将不胜感激任何帮助。

4

2 回答 2

3

简单功能:

processTrackPoints :: [TrackPoint] -> [(Integer, Float, Float)]
processTrackPoints tps = 
  map (\tp -> (time tp, distance tp, speed tp)) $
  filter (\tp -> rpm tp > 10000) tps

相同,但尽可能无点:

processTrackPoints :: [TrackPoint] -> [(Integer, Float, Float)]
processTrackPoints = 
  map (\tp -> (time tp, distance tp, speed tp)) .
  filter ((> 10000) . rpm)

使用警卫:

processTrackPoints :: [TrackPoint] -> [(Integer, Float, Float)]
processTrackPoints ((TP rpm time distance speed) : t)
  | rpm > 10000 = (time, distance, speed) : processTrackPoints t
  | otherwise = processTrackPoints t
processTrackPoints _ = []

当然,这就是所有假设,您已经正确定义了数据类型,如下所示:

data TrackPoint = 
  TP { 
    rpm :: Integer, 
    time :: Integer, 
    distance :: Float, 
    speed :: Float 
  } 
  deriving (Show)
于 2013-04-28T17:20:59.793 回答
1

用推导很容易做到:

[ (time, distance, speed)
| TP rpm time distance speed <- trackPoints
, rpm < 10000
]

更容易{-# LANGUAGE RecordWildCards #-}

[ (time, distance, speed)
| TP{..} <- trackPoints
, rpm < 10000
]

Haskell 中记录的约定通常是为它们添加前缀以避免名称冲突,例如tpRpm. 还值得记住的是,列表推导式只是列表单子的糖:

timesDistancesAndSpeedsOrSomeBetterName <- do
  TP{..} <- trackPoints
  guard (rpm < 10000)
  return (time, distance, speed)
于 2013-04-28T17:19:55.750 回答