Fwd: [Haskell-cafe] Deconstruction

Alberto G. Corona agocorona at gmail.com
Sat Dec 26 06:49:07 EST 2009


Cast uses unsafeCoerce. but well, it´s more elegant ;)


2009/12/26 Miguel Mitrofanov <miguelimo38 at yandex.ru>

> On 26 Dec 2009, at 12:45, Alberto G. Corona wrote:
>
> You can also make use of Typeable and unsafeCoerce  (Data.Dynamic style)
>>
>>
>> data Bar = forall a. (BarLike a, Typeable a) => Bar a
>>
>> unwrapBar :: Bar -> a
>> unwrapBar (Bar x) = case typeof x== typeof  a of
>>                                   True -> unsafeCoerce x
>>                                   False -> error  $ "casting error for
>> type: "++ typeOf a
>>
>
> That's gross. Don't use unsafe functions unless you really need one.
>
>
> data Bar = forall a. (BarLike a, Typeable a) => Bar a
> unwrapBar :: Typeable a => Bar -> a
> unwrapBar (Bar x) = fromMaybe (error $ "casting error for type: " ++ show
> (typeOf x)) $ cast x
>
>
>


>
>
>>
>>
>> 2009/12/26 Miguel Mitrofanov <miguelimo38 at yandex.ru>
>>
>> On 26 Dec 2009, at 11:58, haskell at kudling.de wrote:
>>
>> class BarLike a where
>>   doSomething :: a -> Double
>>
>> data Bar = forall a. BarLike a => Bar a
>>
>> unwrapBar :: Bar -> a
>> unwrapBar (Bar x) = x
>>
>> How can i deconstruct the enclosed value of type a?
>>
>> You can't write a function with a type that mentions existentially
>> quantified "a". Period.
>>
>> But you can deconstruct the enclosed value temporarily:
>>
>> getSomething :: Bar -> Double
>> getSomething b =
>>   case b of
>>       Bar a -> doSomething a
>>
>> _______________________________________________
>> Haskell-Cafe mailing list
>> Haskell-Cafe at haskell.org
>> http://www.haskell.org/mailman/listinfo/haskell-cafe
>>
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20091226/34a30dae/attachment.html


More information about the Haskell-Cafe mailing list