4 ms·
Rust has a good approach here as well, that's related to Haskell's approach. In Rust, a type can implement the traits `Encodable` and `Decodable`, which are gen
by eridius 12y ago
Rust has a good approach here as well, that's related to Haskell's approach. In Rust, a type can implement the traits `Encodable` and `Decodable`, which are general traits that represent the ability to encode to and decode from some arbitrary format, using objects of type Encoder and Decoder. Each supported format then provides implementations of Encoder / Decoder. The benefit of this approach is the Encodable/Decodable implementations can be automatically derived in a lot of cases.
For JSON specifically, the serialize::json module provides Encoder/Decoder implementations, as well as a streaming JSON parser type that can be used to consume JSON outside of the Encodable/Decodable system, and a Builder object that consumes the streaming parser to produce a generic untyped "Json" value that represents the entire structure of the Json. And of course it has some convenience functions that simplify common operations like encoding a value into a string.
Given all this, the equivalent of the Haskell operations looks like:
let v: Json = ...; // get the Json value
// the following traverses the Json to extract the same path as the Haskell
// and treats the result as a 64-bit integer.
// note: this API is slightly old and has some unnecessary stuff in here,
// such as the find method taking allocated strings instead of slices.
let x: Option<i64> = v.find_path([&"foo".to_string(), &"bar".to_string(), &"baz".to_string()])
// this should eventually become .find_path(["foo", "bar", "baz"])
.and_then(|obj| obj.as_list())
.and_then(|l| l.as_slice().get(3))
// the .as_slice() will go away
.and_then(|val| val.as_i64());
There's talk of adding support for `do` sugar which would make this much simpler as well.
The typed version is much simpler. We can define the struct with a derived Decodable like so:
#[deriving(Decodable)]
struct Point {
x: f64,
y: f64
}
And then actually decode some Json like
let x: json::DecodeResult<Point> = json::decode(source_str);
// DecodeResult contains either the result, or an error.
- tel 12y agoTo be clear, you can autoderive the JSON encoding for Aeson, too. I just wanted to demonstrate the full thing. Also, the XPath implementation I noted is special over Rust's because it forms a Lens (Prism, really) so you can get and set at arbitrary positions or even sequences of positions: v & ix 3 . each . _Integer %~ succ The above increments each integer in the array stored at index 3 of `v` if one exists.
- riffraff 12y agopardon my ignorance, but in the last line, how does json::decode knows it should decode to a json::DecodeResult<Point> rather than a json::DecodeResult<Whatever> ?
- eridius 12y agoBecause of the type annotation on the `x` declaration. Rust takes type constraints on the result type into account when determining what implementation to call.