I need help translating an OO concept into Haskell.
Imagine a Vehicle
class and Car
and Truck
subclasses, with a driveOneMile
method that returns a double representing the total fuel used. Each call to driveOneMile
also changes the internal state of the vehicle.
This is what I've done so far in Haskell (since there are no instance variables in Haskell, it seems I have to create my own "state" types):
type CarState = (Double,Double)
initialCarState = (0,0)
driveCarOneMile :: CarState -> (Double,CarState) --Double: total fuel used
driveCarOneMile s = ...
--the internal state of trucks is more complex. needs three Doubles
type TruckState = (Double,Double,Double)
initialTruckState = (0,0,0)
driveTruckOneMile :: TruckState -> (Double,TruckState)
driveTruckOneMile s = ...
In a similar way I could construct other vehicles and their "drive" functions.
This is how I would drive a car twice:
fuelFor2Miles = fst $ driveCarOneMile $ snd $ driveCarOneMile initialCarState
- Am I doing this correctly?
- If not, how would you correct it?
- How can I use the above (or your corrected way) to take a collection of many cars, trucks, and other vehicles, drive each of them 10 times, and get the corresponding [Double] list of the total fuel used? (In OO this would be a simple matter of throwing the vehicles into a list, calling the method on each of them 10 times, and putting the total fuel used into a new list.)