Skip to content

Conversation

@codegod100
Copy link

This PR updates the EncodeDecode example to use the new Roc static dispatch syntax.

Changes

  • Replace old abilities-based encoding with new static dispatch using where clauses
  • Demonstrate encode_str and encode_list method requirements
  • Add custom type encoding with Person example showing nested encoding
  • Update README with new syntax documentation and expected output

Note

This example uses new Roc syntax (static dispatch, match, var, etc.) and will work once the examples repo is updated to new Roc.

Based on: roc-lang/roc@22cf61f

cc @Anton-4 - migrated from roc-lang/basic-cli#415 per your suggestion

- Replace old abilities-based encoding with new static dispatch
- Demonstrate where clauses for encode_str and encode_list
- Show custom type encoding with Person example
- Update README with new syntax and expected output

Note: This example uses new Roc syntax and will work once the examples repo is updated to new Roc.
Copy link
Collaborator

@Anton-4 Anton-4 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @codegod100 :)

I would like to split this up into two examples:

  1. Minimal encode-decode example: Easily digestible for human brains.
  2. Larger, more advanced encode-decode example

Maybe we should wait with updating till we have more auto derive stuff implemented in the new compiler? That will change the code a lot.

  • We should also update this to a notebook file format once that is implemented in the new compiler. That makes it easy to ensure all code in the .md file stays up-to-date.

Comment on lines 42 to 66
# Define a Person type that can be encoded as a JSON object
Person := [Person({ name : Str, age : U64 })].{
# Custom encode method for Person - encodes as JSON object
encode : Person, JsonFormat -> List(U8)
encode = |self, fmt| {
# Get the inner record via pattern match
match self {
Person({ name, age }) => {
# Encode name as JSON string
name_bytes = name.encode(fmt)

# Encode age as number (no quotes)
age_bytes = Str.to_utf8(age.to_str())

# Build: {"name":"...","age":...}
var $result = Str.to_utf8("{\"name\":")
$result = $result.concat(name_bytes)
$result = $result.concat(Str.to_utf8(",\"age\":"))
$result = $result.concat(age_bytes)
$result = $result.concat(Str.to_utf8("}"))
$result
}
}
}
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe this will be more auto derived in the future, can you add a TODO comment above this to make this use auto derive when it is implemented?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants