I can’t seem to alter the posts after a couple of days. Shame, else I would’ve added those new suggestions to the “solution”.
Do you know Julian date number? You can easily calculate the weekdays for the given Julian date
@polarit I’m not a maths person, explain how modBy
manages to do that? This seems theoretically cool, but relies on building out a library for that functionality. I’m not sure how practical that would be as appose to using Elm’s time package
> import List.Extra exposing (zip)
> zip wdNrs wdNames
[(1,"Mon"),(2,"Tue"),(3,"Wed"),(4,"Thu"),(5,"Fri"),(6,"Sat"),(7,"Sun")]
: List ( Int, String )
The zip
function is also cool, though might be better calling getIndex
function on wdNames
(at least if there’s an unknown length to the list).
getIndex list =
(range 0 ((List.length list - 1)))
Again like you’ve both noted, I’m not sure how much we’d need to worry about speed — “Shape of a function” is quite a good bit of SICP and brings up these questions:
- Is a flat shape considered faster and more performant?
- Is there an Elm stepper repl somewhere, like Dr. Racket?
- Or any good guides you could pass on for performance?
@lydell So both List.map2
and List.indexedMap
are the same speed?
Summing up
I’ve created a final little program mushing together what’s been talked about. Judging by what we’ve covered in this thread, keeping things concise and making use of built-in List
functions makes things a whole lot easier to reason about. My first attempt is a lot harder to follow.
I wish there was a function that did everything from line 33
onwards though. You’ve still got to do something like this to make use of all our hard work:
pluckDay : Index -> Day
pluckDay i =
case (List.head (filterDay i)) of
Just day ->
(Tuple.second day)
Nothing ->
"It's always a Monday!"
Going forward
So there’s a few questions we’ve covered, or that I need to consider further (don’t worry I’m not looking for answers!):
- When should I use a recursive function? (when it’s simple, I would say)
- When is it wiser to use a built in
List
function? (most of the time it seems)
- What to do about finite lists? (use a
Set DayTuple
?)
- Using a simple
case
-vs- creating a Tuple.pair
(the simple case
might actually be preferable)
- “Plucking” the
DayTuple
we want to use (remove as many steps as you can to get to this point)
- If we were building a simple calendar, say, what’s the sane way to do this with existing libraries? (using
Time
etc)
I guess this is all good practice and, although I think the solution I’ve linked to might be overkill for a simple day-finder, it’s been a good exercise seeing what’s possible with Elm.
It seems a good many things are already “solved problems” in the core libraries!
Thanks guys
Useful functions for recursion:
map
, map2
, indexedMap
(the example there does everything I wanted), zip
as an alternative to indexedMap
, and filter
. The rest you can see in the examples above.