Last active
October 10, 2015 11:58
-
-
Save folone/3686930 to your computer and use it in GitHub Desktop.
Pointers
This file contains hidden or 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
| class Monad m => Ref r m where | |
| ref :: a -> m (r a) | |
| (*) :: r a -> m a | |
| (*=) :: r a -> a -> m () | |
| (*$) :: r a -> (a -> a) -> m () | |
| r *$ f = (r *) >>= (*=) r . f | |
| instance Ref IORef IO where | |
| ref = newIORef | |
| (*) = readIORef | |
| (*=) = writeIORef | |
| instance Typeable t => Show (IORef t) where | |
| show _ = "IORef " ++ show (typeOf (undefined :: t)) | |
| f r v = r *= v | |
| main = do | |
| y :: IORef Int <- ref 10 | |
| print y | |
| print =<< (y *) | |
| f y 25 | |
| print =<< (y *) | |
| y *$ (+ 35) | |
| print =<< (y *) | |
| -- IORef Int | |
| -- 10 | |
| -- 25 | |
| -- 60 |
This file contains hidden or 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
| class *[T](var value: T) { | |
| def *=(t: T) { | |
| value = t | |
| } | |
| def *() = value | |
| override def toString = "ref to " + value | |
| } | |
| object * { | |
| def &[T](x: T) = new *(x) | |
| } | |
| object RefTest { | |
| import *._ | |
| def f(v:Int, x: *[Int]) { | |
| x*=v | |
| } | |
| def main(args: Array[String]) { | |
| val y = &(1) | |
| println(y*) | |
| println(y) | |
| f(3, y) | |
| println(y*) | |
| println(y) | |
| } | |
| } | |
| // 1 | |
| // ref to 1 | |
| // 3 | |
| // ref to 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment