[Haskell-cafe] Advice needed on how to improve some code
Tom Ellis
tom-lists-haskell-cafe-2013 at jaguarpaw.co.uk
Thu Apr 16 06:03:14 UTC 2015
On Thu, Apr 16, 2015 at 10:57:41AM +1000, Jeff wrote:
> ( \pl' -> let pld = P.payloadData pl' in
> if testBit mdm ( fromEnum D.GPS )
> then
> parseDeviceGPSData >>=
> ( \s -> return ( pl' { P.payloadData = pld { P.gpsData = Just s } } ) )
> else
> return pl' ) >>=
> ( \pl' -> let pld = P.payloadData pl' in
> if testBit mdm ( fromEnum D.GSM )
> then
> parseDeviceGSMData >>=
> ( \s -> return ( pl' { P.payloadData = pld { P.gsmData = Just s } } ) )
> else
> return pl' ) >>=
> ( \pl' -> let pld = P.payloadData pl' in
> if testBit mdm ( fromEnum D.COT )
> then
> parseDeviceCOTData >>=
> ( \s -> return ( pl' { P.payloadData = pld { P.cotData = Just s } } ) )
The first thing you should do is define
parseDeviceGPSDataOf constructor parser setField =
( \pl' -> let pld = P.payloadData pl' in
if testBit mdm ( fromEnum constructor )
then
parser >>=
( \s -> return ( pl' { P.payloadData = setField pld (Just s) } } ) )
else
return pl' )
and your chain of binds will become
setgpsData pld = pld { P.gpsData = Just s }
...
parseDeviceDataOf D.GPS parseDeviceGPSData setgpsData >>=
parseDeviceDataOf D.GSM parseDeviceDSMData setgsmData >>=
parseDeviceDataOf D.COT parseDeviceCOTData setcotData >>=
...
Then I would probably write
deviceSpecs = [ (D.GPS, parseDeviceGPSData, setgpsData)
, (D.GSM, parseDeviceDSMData, setgsmData)
, (D.COT, parseDeviceCOTData, setcotData) ]
and turn the chain of binds into a fold.
Tom
More information about the Haskell-Cafe
mailing list