Skip to content

Commit

Permalink
fix State definition (#11)
Browse files Browse the repository at this point in the history
  • Loading branch information
gcanti committed Feb 28, 2017
1 parent 82c367b commit 63644f5
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 3 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Expand Up @@ -21,6 +21,9 @@
- add NonEmptyArray, fix #12 (@gcanti)
- **Polish**
- add tslint
- **Bug Fix**
- fix `State` definition (@gcanti)


# 0.0.2

Expand Down
12 changes: 9 additions & 3 deletions src/State.ts
Expand Up @@ -20,13 +20,19 @@ export class State<S, A> implements HKTState<S, A> {
return this.run(s)[1]
}
map<B>(f: Function1<A, B>): State<S, B> {
return new State<S, B>(s => [f(this.eval(s)), s])
return new State<S, B>(s => {
const [a, s1] = this.run(s)
return [f(a), s1]
})
}
ap<B>(fab: State<S, Function1<A, B>>): State<S, B> {
return fab.chain(f => map(f, this)) // <= derived
}
chain<B>(f: Function1<A, State<S, B>>): State<S, B> {
return new State<S, B>(s => (f(this.eval(s))).run(s))
return new State<S, B>(s => {
const [a, s1] = this.run(s)
return f(a).run(s1)
})
}
}

Expand Down Expand Up @@ -59,7 +65,7 @@ export function modify<S>(f: Endomorphism<S>): State<S, void> {
}

export function gets<S, A>(f: Function1<S, A>): State<S, A> {
return get<S>().chain(s => of<S, A>(f(s)))
return new State<S, A>(s => [f(s), s])
}

// tslint:disable-next-line no-unused-expression
Expand Down
40 changes: 40 additions & 0 deletions test/State.ts
@@ -0,0 +1,40 @@
import * as assert from 'assert'
import {
put,
get,
modify,
gets,
State
} from '../src/State'

describe('State', () => {
it('put', () => {
assert.deepEqual(put(2).run(1), [undefined, 2])
})

it('get', () => {
assert.deepEqual(get().run(1), [1, 1])
})

it('modify', () => {
const double = (n: number) => n * 2
assert.deepEqual(modify(double).run(1), [undefined, 2])
})

it('gets', () => {
const double = (n: number) => n * 2
assert.deepEqual(gets(double).run(1), [2, 1])
})

it('map', () => {
const double = (n: number) => n * 2
const state = new State<number, number>(s => [s - 1, s + 1])
assert.deepEqual(state.map(double).run(0), [-2, 1])
})

it('chain', () => {
const f = (n: number) => new State<number, number>(s => [s - 1, s + 1])
const state = new State<number, number>(s => [s - 1, s + 1])
assert.deepEqual(state.chain(f).run(0), [0, 2])
})
})

0 comments on commit 63644f5

Please sign in to comment.