Mapping and Reducing Flights: A Haskell Exploration
- Serjo Agronov
- Haskell , Web frameworks
- April 4, 2022
- Reading time: 2 minutes
Mapping and Reducing Flights: A Haskell Exploration
Haskell, a champion of functional programming, offers powerful tools for manipulating data. Two fundamental concepts are "map" and "reduce" (also known as "fold"). Let's see how these work by managing a hypothetical list of airplanes and airfields.
Scenario
Imagine you're building a basic flight tracker. You have the following data structures:
data Airfield = Airfield { airfieldCode :: String,
airfieldName :: String } deriving Show
data Airplane = Airplane { planeModel :: String,
airfieldCode :: String } deriving Show
Beginner Level
1. Mapping: Applying Changes to Every Flight
Let's say you want a list of all airplane models. 'map' is your friend:
airplanes = [Airplane "Boeing 737" "JFK", Airplane "Airbus A320" "LHR"]
planeModels = map planeModel airplanes
-- Result: ["Boeing 737", "Airbus A320"]
2. Reduce / Fold: Calculating Total Number of Airfields
Want to know how many unique airfields your planes use? Use 'foldl':
countAirfields :: [Airplane] -> Int
countAirfields planes = length (foldl addAirfield [] airplanes)
addAirfield :: [String] -> Airplane -> [String]
addAirfield visitedCodes plane =
if airfieldCode plane `elem` visitedCodes then visitedCodes
else airfieldCode plane : visitedCodes
Advanced Level
1. More Powerful Mapping with Functors
Haskell's Functor
class takes mapping to the next level. Let's adjust the destination airfield for every flight:
instance Functor Airplane where
fmap f (Airplane model code) = Airplane model (f code)
shiftDestination :: String -> String
shiftDestination code = code ++ "-ALT" -- Example: Changes JFK to JFK-ALT
shiftedPlanes = fmap shiftDestination airplanes
2. Fold Variations: foldr and Custom Folds
For summing plane capacities (hypothetically):
data Airplane = Airplane { planeModel :: String,
airfieldCode :: String,
capacity :: Int
} deriving Show
totalCapacity foldFunc planes = foldFunc 0 planes
-- Standard: foldl
totalCapacityWithFoldl _ plane = capacity plane + acc
-- Right-associative: foldr
totalCapacityWithFoldr acc plane = acc + capacity plane
Notes:
- This requires basic Haskell knowledge.
- Consider a library like 'lens' for advanced data manipulation in real projects.