[elm-discuss] Re: Looking for a better way to use `andThen` chains (and other beginner questions)

2017-04-23 Thread Max Goldstein

>
> If you're looking for a somewhat broader background on data modeling in 
> Elm, this talk is a must-watch: Making Impossible States Impossible
>

Sorry, looks like the YouTube link got put at the top of the post. 

-- 
You received this message because you are subscribed to the Google Groups "Elm 
Discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to elm-discuss+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


[elm-discuss] Re: Looking for a better way to use `andThen` chains (and other beginner questions)

2017-04-23 Thread Max Goldstein
https://www.youtube.com/watch?v=IcgmSRJHu_8Instead of lists with numbered 
items, have you thought about using a dictionary 
? Something 
like this?

import Dict exposing (Dict)

type alias No = Int
type alias Game = { stars : Dict No Star, teams : Dict No Team }
type alias Team = { name : String, color : String, species : String }
type alias Star = { name : String, planets : Dict No Planet }
type alias Planet = { name : String, minerals : Int, colony : Maybe Colony }
type alias Colony = { team : No, defense : Int }

getStarPlanet : No -> No -> Game -> Result String Planet
getStarPlanet starNo planetNo {stars} =
  Dict.get starNo stars
|> Result.fromMaybe "Star not found"
|> Result.andThen (\{planets} -> Dict.get planetNo planets |> 
Result.fromMaybe "Planet not found")

It's still a little repetitive, and you need to nest a Result.fromMaybe 
inside a Result.andThen callback, but it works. (You should maybe consider 
a union type for these errors instead of strings.) 

I've also tried to anticipate that you'll have uncolonized planets, which 
will still have things like minerals, size, atmosphere, temperature, things 
like that. Some of those will also have colonies which will have a team, 
defense, buildings, colonists, and so on.

Incidentally, if you're okay fixing the number of teams at compile-time, 
you might be able to avoid the inconsistent state of a colony whose team is 
not in the team dictionary.

type TeamNo = Red | Blue
type alias Teams = { red : Team, blue : Team }
getTeam : TeamNo -> Teams -> Team
getTeam no teams =
  if no == Red then teams.red else teams.blue

If you're looking for a somewhat broader background on data modeling in 
Elm, this talk is a must-watch: Making Impossible States Impossible

-- 
You received this message because you are subscribed to the Google Groups "Elm 
Discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to elm-discuss+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.