Last active
May 30, 2017 19:52
-
-
Save hallettj/494ab85865fea0d73a4793fd0a2bbb64 to your computer and use it in GitHub Desktop.
Example of a graph in Elm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Html exposing (text) | |
import List exposing (concatMap, filter) | |
import List.Extra exposing (uniqueBy) | |
type alias CityId = Int | |
type alias City = | |
{ id: CityId | |
, name: String | |
} | |
type alias Route = | |
{ from: City | |
, to: City | |
, trafficLevel: Float | |
} | |
type alias World = | |
{ cities: List City -- not really necessary, except perhaps as a memoization optimization | |
, routes: List Route | |
} | |
portland = { id = 1, name = "Portland" } | |
seattle = { id = 2, name = "Seattle" } | |
vancouver = { id = 3, name = "Vancouver" } | |
newWorld routes = | |
{ cities = citiesFromRoutes routes | |
, routes = routes | |
} | |
citiesFromRoutes : List Route -> List City | |
citiesFromRoutes routes = | |
let | |
allCities = concatMap (\r -> [r.from, r.to]) routes | |
in | |
uniqueBy (\c -> c.id) allCities | |
world = newWorld | |
[ { from = portland, to = seattle, trafficLevel = 4 } | |
, { from = portland, to = vancouver, trafficLevel = 3 } | |
, { from = seattle, to = portland, trafficLevel = 2 } | |
, { from = vancouver, to = portland, trafficLevel = 0 } | |
] | |
routesFrom city world = | |
filter (\r -> r.from.id == city.id) world.routes | |
fromPortland = routesFrom portland | |
routesBetween origin destination world = | |
filter (\r -> r.from.id == origin.id && r.to.id == destination.id) world.routes | |
main = text (toString (routesBetween portland vancouver world)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment