Stream: beginners

Topic: Encoding Ability for single purpose write to file


view this post on Zulip Johan Lindskogen (Jan 03 2024 at 11:27):

I want to write a struct to a file using a special encoding only for this struct. Is this a weird use-case for the Encoding ability? Should I just write uft8 strings to a List ("buffer") and then write to a file?

This is what I got so far:

Color : { r : U8, g : U8, b : U8 }
PPM: { width: U32, height: U32, data: List Color }

header = \width, height ->
    "P3\n\(Num.toStr width) \(Num.toStr height)\n255"

ppmEncode : PPM -> Encoding
ppmEncode = \{width, height, data} ->
    Encode.custom \bytes ->
        List.concat bytes (Str.toUtf8 (header width height))
        |> List.concat (List.map data \{r, g, b} -> (Str.toUtf8 "\(Num.toStr r) \(Num.toStr g) \(Num.toStr b)"))


main =
    File.write
    (Path.fromStr "output.json")
    { width: 256, height: 256, data: [{ r: 0, g: 0, b: 0 }, {r: 1, g: 0, b: 0}, {r: 2, g: 0, b: 0}]}
    ppmEncode

I'm expecting the output to be like this:

P3
256 256
255
0 0 0
1 0 0
2 0 0
3 0 0
4 0 0
5 0 0
6 0 0
7 0 0
8 0 0
9 0 0
10 0 0
11 0 0
...

view this post on Zulip Brendan Hansknecht (Jan 03 2024 at 17:13):

I would probably generate the Str or List U8 directly. Cause you don't really have a full encoder. A generic PPM Encoder that depends on the Encoder ability doesn't really make sense. It can't be used to encode arbitrary types to the format, which is what encode is for.

view this post on Zulip Brendan Hansknecht (Jan 03 2024 at 17:14):

Like a JSON or Protobuf or BSON encoder make sense...Maybe there is a way to make a PPM encoder, but I don't think it really fits

view this post on Zulip Brendan Hansknecht (Jan 03 2024 at 17:15):

You could define a PPM type that encodes to a specific value (which looks to be what you are trying to do), but that would just enable encoding a PPM as a JSON/Protobuf/etc field, which really isn't the goal

view this post on Zulip Johan Lindskogen (Jan 03 2024 at 18:39):

Thank you for the patient response :blush: I ended up using a List U8 instead

view this post on Zulip Johan Lindskogen (Jan 03 2024 at 23:56):

Made some more progress with my raytracer! This is where I got so far! https://github.com/lindskogen/roc-raytracer
image.png

view this post on Zulip Brendan Hansknecht (Jan 04 2024 at 00:17):

Nice


Last updated: Jul 06 2025 at 12:14 UTC