Skip to content

Instantly share code, notes, and snippets.

@aaronlifton
Forked from hallettj/routes.elm
Created May 30, 2017 19:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaronlifton/3d2dec590f5be736ec2849b882e62000 to your computer and use it in GitHub Desktop.
Save aaronlifton/3d2dec590f5be736ec2849b882e62000 to your computer and use it in GitHub Desktop.
Example of a graph in Elm
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