Embrace connections to functional programming #2724
-
Jotai is a very exciting library because it is a state monad: const pure = atom satisfies (<T>(a: T) => Atom<T>)
function map<T, V>(anAtom: Atom<T>, fn: (a: T) => V): Atom<V> {
return atom((get) => fn(get(anAtom)))
}
function join<T>(nestedAtoms: Atom<Atom<T>>): Atom<T> {
return atom((get) => get(get(nestedAtoms)))
} Notably, the atom getter is Haskell's monad do-notation (and by extension, JavaScript's own const xAtom = atom(0)
const yAtom = atom(0)
const vAtom = atom((get) => {
const x = get(xAtom)
const y = get(yAtom)
return { x, y }
}) with const xPending = Promise.resolve(0)
const yPending = Promise.resolve(0)
const vPending = (async function() {
const x = await xPending
const y = await yPending
return { x, y }
})() and (in Haskell) xAtom = atom 0
yAtom = atom 0
vAtom = do
x <- xAtom
y <- yAtom
return $ V2 x y DocumentationI think the fact that Jotai is a monad should be mentioned in the README:
Quality of life improvementAs a separate wish, I think adding the const line = (m: number, b: number) => (x: number) => m * x + b
const xAtom = atom(0)
const yAtom = xAtom.map(line(3, 10)) Moreover, |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 16 replies
-
Hey, thanks for opening up the discussion.
I think I almost understand what is said, but tbh, I'm not super familiar with FP.
I wouldn't add such capabilities to |
Beta Was this translation helpful? Give feedback.
-
@probeiuscorp Can you check this thread? https://x.com/hiddenwaterways/status/1832621724351050117 |
Beta Was this translation helpful? Give feedback.
Docs PR is in! #2726