Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Serialization of data types #31

Closed
gcanti opened this issue Mar 11, 2017 · 2 comments
Closed

Serialization of data types #31

gcanti opened this issue Mar 11, 2017 · 2 comments

Comments

@gcanti
Copy link
Owner

gcanti commented Mar 11, 2017

This is what I get from Option now

import { fromNullable } from 'fp-ts/lib/Option'

const x = fromNullable(1)
const y = fromNullable(null)

console.log(JSON.stringify(x)) // => {"value":1}
console.log(JSON.stringify(y)) // => {}

In order to behave more like flow-static-land which doesn't change the underline representation when you call inj / prj, would be useful a toNullable function

declare function toNullable<A>(fa: HKTOption<A>): A | null

such that the pair inj / prj is equivalent to the pair fromNullable / toNullable. Also both None and Some could implement the toJSON method.

Proof of concept

export class None<A> {
  ...
  toJSON(): null {
    return null
  }
}

export class Some<A> {
  ...
  toJSON(): A {
    return this.value
  }
}

export function fromNullable<A>(a: A | null | undefined): Option<A> {
  return a == null ? none : new Some(a)
}

export function toNullable<A>(fa: HKTOption<A>): A | null {
  return (fa as Option<A>).toJSON()
}

Result

const x = fromNullable(1)
const y = fromNullable(null)

console.log(toNullable(x)) // => 1
console.log(toNullable(y)) // => null

console.log(JSON.stringify(x)) // => 1
console.log(JSON.stringify(y)) // => null

/cc @danielepolencic

@danielepolencic
Copy link

danielepolencic commented Mar 11, 2017

Initially this is what I had.

The problem I faced is that - while the .toJSON solves the serialisation - there's no easy way to
deserialise the data structure.

As an example, I'm using a redux-like framework and messages and state are plain objects by definition. When I wrapped my Maybes into classes, I had to have ser/deser functions all over codebase. This made the code more complicated and bloated.

For data types such as Maybe and Either, it makes sense to have the data type as a plain object. In that way there's no need to transform the data into the proper data type.

@gcanti
Copy link
Owner Author

gcanti commented Mar 13, 2017

Ops, sorry, wrong repo. Moving to gcanti/fp-ts#18

@gcanti gcanti closed this as completed Mar 13, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants