# [Haskell-cafe] Trick to have existential type work in this case?

YueCompl compl.yue at icloud.com
Mon Apr 19 08:23:16 UTC 2021

```What a concise explanation and practical solutions! Thanks!

And your 2nd solution really updated my knowledge about CPS, I used to assume some "continuation" always has to be passed around in CPS, now I know it can be used for nesting of scopes, and to have it naturally "return" back to outer scope.

Thanks with best regards!

> On 2021-04-16, at 02:27, Albert Y. C. Lai <trebla at vex.net> wrote:
>
> On 2021-04-15 8:54 a.m., YueCompl via Haskell-Cafe wrote:
>>
>> -- * Things not working
>>
>> managedArrayAsSeries :: SomeManagedArray -> IO Dynamic
>> managedArrayAsSeries (SomeManagedArray ma) = do
>>   vec <- do
>>     SomeArray cap fp <- arrayAtTheMoment ma
>>     return \$ VS.unsafeFromForeignPtr0 fp cap
>>
>>   let len = return \$ VS.length vec
>>       rs i = return \$ vec VS.! i
>>   return \$ toDyn \$ Series len rs
>>
> That means you have this code fragment:
>
> arrayAtTheMoment ma
> >>=
> \(SomeArray cap fp) -> return \$ VS.unsafeFromForeignPtr0 fp cap
> That means you have this function:
>
> \(SomeArray cap fp) -> return \$ VS.unsafeFromForeignPtr0 fp cap
> Now you are violating the 1st restriction at
> There are two solutions.
>
> 1st solution: One more existential type.
>
> data Vec = forall a. (Typeable a, VS.Storable a) => Vec (VS.Vector a)
>
>   Vec vec <- do
>     SomeArray cap fp <- arrayAtTheMoment ma
>     return (Vec (VS.unsafeFromForeignPtr0 fp cap))
> 2nd solution: CPS transform.
>
> {-# language RankNTypes #-}
> {-# language BlockArguments #-}
>
> withSomeArray :: SomeArray
>               -> (forall a. (Typeable a, VS.Storable a) => Int -> ForeignPtr a -> r)
>               -> r
> withSomeArray (SomeArray i p) f = f i p
>
> sa <- arrayAtTheMoment ma
> withSomeArray sa \cap fp -> do
>   let vec = VS.unsafeFromForeignPtr0 fp cap
>       -- or if you prefer: vec <- return (VS.unsafeFromForeignPtr0 fp cap)
>       len = return (VS.length vec)
>       rs i = return (vec VS.! i)
>       etc.
> _______________________________________________