2013-04-28 55 views
3

Haskell的全新功能。 Problem-我有由4個分量的值構造類型構造:從列表中提取Haskell中的單個整數

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

我想利用[指點杆],並將它返回時間,距離和速度隨時的rpm值低於10,000。我曾嘗試過使用警衛而沒有運氣。任何幫助將受到這個新手的讚賞。

+1

你試過了什麼?您能否提供一些具有相應輸出的示例輸入? – hammar 2013-04-28 17:21:42

回答

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) 
+0

謝謝,會試試看。 – user2328270 2013-04-28 20:14:01

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)