Magical function to support reflection

Kiss Csongor kiss.csongor.kiss at gmail.com
Fri Jan 20 14:54:03 UTC 2017


The problem is in the reify function:

```
reify :: forall a r. a -> (forall (s :: *). Reifies s a => Proxy s -> r) -> r
reify a k = unsafeCoerce (Magic k :: Magic a r) (const a) Proxy
```
here, unsafeCoerce coerces `const a` to type `a`, in the concrete case, to Int.
```
*Main> unsafeCoerce (const 5) :: Int
1099511628032
```
this is indeed what seems to be the issue:
```
*Main> reify 5 reflect
1099511628032
```
which is why test1 then shows the wrong result.

Also, in the Magic newtype, there’s a `Proxy s`, which afaik doesn’t have the expected runtime representation
`a -> r`. (there’s a proxy in the middle, `a -> Proxy -> r`).

Changing Magic to
```
newtype Magic a r = Magic (forall (s :: *) . Reifies s a => Tagged s r)
```
now has the correct runtime rep, and the reification can be done by coercing the Magic in to `a -> r`, as such
```
reify' :: a -> (forall (s :: *) . Reifies s a => Tagged s r) -> r
reify' a f = unsafeCoerce (Magic f) a
```

the Proxy version is just a convenience, wrapped around the magic one:

```
reify :: forall r a. a -> (forall (s :: *) . Reifies s a => Proxy s -> r) -> r
reify a f = reify' a (unproxy f)
```

Here’s the complete file, with the changes that compile and now work:

https://gist.github.com/kcsongor/b2f829b2b60022505b7e48b1360d2679 <https://gist.github.com/kcsongor/b2f829b2b60022505b7e48b1360d2679>

— Csongor

> On 20 Jan 2017, at 14:14, Matthew Pickering <matthewtpickering at gmail.com> wrote:
> 
> I modified the example on the wiki to compile but I seem to have
> missed something, could you perhaps point out what I missed?
> 
> https://gist.github.com/mpickering/da6d7852af2f6c8f59f80ce726baa864
> 
> ```
> *Main> test1 2 123 441212
> 441335
> ```
> 
> On Thu, Jan 19, 2017 at 3:58 AM, David Feuer <david at well-typed.com> wrote:
>> I've updated https://ghc.haskell.org/trac/ghc/wiki/MagicalReflectionSupport to
>> reflect both Simon's thoughts on the matter and my own reactions to them. I
>> hope you'll give it a peek.
>> 
>> David Feuer
>> _______________________________________________
>> ghc-devs mailing list
>> ghc-devs at haskell.org
>> http://mail.haskell.org/cgi-bin/mailman/listinfo/ghc-devs
> _______________________________________________
> ghc-devs mailing list
> ghc-devs at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/ghc-devs

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/ghc-devs/attachments/20170120/c45ca514/attachment.html>


More information about the ghc-devs mailing list