Created
August 29, 2012 01:55
-
-
Save brehaut/3506039 to your computer and use it in GitHub Desktop.
mutable refs in Roy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// the first hack needed to support mutable refs in Roy is allowing in place edits | |
// to JS arrays | |
let aSet (arr:[#a]) (idx:Number) (v:#a) :[#a] = | |
Array.prototype.splice.call arr idx 1 v | |
arr | |
// wrapper type is currently a structural type rather than an ADT because I couldn't | |
// get ADTs to have an Array as a field | |
type Ref = {_val: [#a]} | |
// functions to operate on a ref | |
let ref v: Ref = {_val: [v]} | |
let setRef (wrapped_v:Ref) new_v :Ref = | |
aSet wrapped_v._val 0 new_v | |
wrapped_v | |
let getRef (wrapped_v:Ref) = wrapped_v._val @ 0 | |
let alterRef (wrapped_v:Ref) (f:Function(#a, #a)) = | |
setRef wrapped_v (f (getRef wrapped_v)) | |
wrapped_v | |
// e.g. | |
let mutable_cell = ref 1 | |
console.log (getRef mutable_cell) | |
//=> 1 | |
setRef mutable_cell 3 | |
console.log (getRef mutable_cell) | |
//=> 3 | |
alterRef mutable_cell (\x -> x * 2) | |
console.log (getRef mutable_cell) | |
//=> 6 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// the first hack needed to support mutable refs in Roy is allowing in place edits | |
// to JS arrays | |
let aSet (arr:[#a]) (idx:Number) (v:#a) :[#a] = | |
Array.prototype.splice.call arr idx 1 v | |
arr | |
// wrapper type is currently a structural type rather than an ADT because I couldn't | |
// get ADTs to have an Array as a field | |
type __Cell = {_val: [#a]} | |
// a second wrapper type that uses ADTs then wraps the __Cell type so that it can be type | |
// checked parametrically in setRef. | |
data RefT a = Ref __Cell | |
// functions to operate on a ref | |
let ref (v:#a): RefT #a = Ref {_val: [v]} | |
let setRef (wrapped_v:RefT #a) (new_v:#a):RefT #a = | |
match wrapped_v | |
case (Ref cell) = aSet cell._val 0 new_v | |
wrapped_v | |
let getRef (wrapped_v:RefT #a):#a = match wrapped_v | |
case (Ref cell) = cell._val @ 0 | |
let alterRef (wrapped_v:RefT #a) (f:Function(#a, #a)) :RefT #a = | |
setRef wrapped_v (f (getRef wrapped_v)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment