Does Elm have an equivalent of Haskell's “Read”

一曲冷凌霜 提交于 2019-12-01 17:48:28

问题


I'm currently writing an online game where I use Haskell for the server-side backend and Elm for the frontend/rendering.

Right now I have my GameState as one big ADT, in a type simple enough that I can use it in Elm as well. I was hoping to avoid using JSON, and simply pass Elm the output of "show" on the data, which I could then parse-back into an ADT in Elm.

I'm wondering, is there anything equivalent to haskell's "read" which can automatically look at a string output by show, and parse it back into data? If not, are there any existing parser-libraries available for Elm?

If I do end up going with JSON, is there a way to automatically convert it into an ADT? (Something similar to Aeson's FromJSON, perhaps?)


回答1:


My understanding is that Elm—not having typeclasses—cannot easily have a polymorphic version of read or fromJSON. I also do not believe it has any good facilities for generic programming, so implementing something akin to deriving or OCaml's with would be difficult as well.

Unfortunately, this means your best bet is to write one-off functions for serializing and deserializing the various types you use. You could use aeson on the Haskell side and then write functions to/from JSON using Elm's JSON library.

Another option may be to try reusing the code produced by Haskell's deriving Read and porting it to Elm. However, this might be more work than it's worth, and I am not sure how to go about it, exactly.



来源:https://stackoverflow.com/questions/18542890/does-elm-have-an-equivalent-of-haskells-read

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!