Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting single integer in Haskell from list

Tags:

haskell

Totally new to Haskell. Problem- I have a type constructor with a value constructor consisting of 4 components:

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

I would like to take [TrackPoint] and have it return time, distance and speed anytime the rpm value is below 10,000. I have tried using guards with no luck. Any help would be appreciated by this novice.

like image 703
user2328270 Avatar asked Sep 05 '26 06:09

user2328270


1 Answers

Simple function:

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

Same, but point-free where possible:

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

Using guards:

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

That is all, of course, assuming, that you have the datatype defined correctly like this:

data TrackPoint = 
  TP { 
    rpm :: Integer, 
    time :: Integer, 
    distance :: Float, 
    speed :: Float 
  } 
  deriving (Show)
like image 135
Nikita Volkov Avatar answered Sep 08 '26 20:09

Nikita Volkov