Hey guys,
I’m rather new to elm and it is my first language in the ML family.
Right now I’m trying to do the AOC 2022 in order to get the hang of it and the first issue is the file selection.
I got it to work but I have several issues with it and I don’t really know how to work arround it but right now it doesn’t really look very “elmy” to me.
My code is at the bottom of this post.
Issues:
My Modesl states (I hope that’s the right name) are alomst identical to the Msg states. That seems weird to me. Mostly I am confused that I need so many Msg states. I thought these are for Ui updates but in my update function I have to throw them around because File.select returns a Task and the same is true for File.toString because it needs to be wrapped in a Task.perform function.
My first idea was to replace most of my Msg states in the update function with the Model states, since the name is mostly identical and they have the same meaning but that looks weird as well since the return type of update chanes from (Model, Cmd Msg) to (Model, Cmd Model) and returning (Model, Cmd Model) just looks wrong to me.
My second issue is that the update function itself seems to long. Isn’t it possible to do the branches FileLoadedMsg and FileParsedMsg in one go?
My third issue is the view function.
The Model states FileLoaded and FileParsed need to exist but what they show is practically useless.
I don’t want them to have default behaviour with “_ → …” so I thought it would be neat if one branch could execute for SelectFile, FileLoaded and FileParsed.
Is something like that possible?
Thanks in advance for any information on how to tackle these issues I’m having.
If you need additional info just leave me a message and I’ll do my best to provide it.
module Day1V2 exposing (…)
import Browser
import Html exposing (…)
import Html.Events exposing (…)
import File exposing (File)
import File.Select as Select
import Platform.Cmd as Cmd
import Task
import Platform.Cmd as Cmd
main =
Browser.element
{ init = init
, update = update
, subscriptions = subscriptions
, view = view
}
init : () → (Model, Cmd Msg)
init _ =
( Init
, Cmd.none
)
– UPDATE
type Msg
= SelectFileMsg
| FileLoadedMsg File
| FileParsedMsg String
– MODEL
type Model
= Init
| SelectFile File
| FileLoaded
| FileParsed
| Success String
update : Msg → Model → (Model, Cmd Msg)
update msg model =
case msg of
SelectFileMsg → (FileLoaded, Select.file [“”] FileLoadedMsg)
FileLoadedMsg file → (FileParsed, Task.perform FileParsedMsg (File.toString file) )
FileParsedMsg file → (Success file, Cmd.none)
– VIEW
view : Model → Html Msg
view model =
case model of
Init →
button [ onClick SelectFileMsg ] [ text “Load File” ]
SelectFile file ->
text "Select file..."
FileLoaded ->
text "Loading..."
FileParsed ->
text "File parsed..."
Success fileText ->
pre [] [ text fileText]
– SUBSCRIPTIONS
subscriptions : Model → Sub Msg
subscriptions model =
Sub.none