[livecode] Re: Vivid: Create a value of type `I a` where `a` is chosen at runtime

From: Claude Heiland-Allen <claude_at_mathr.co.uk>
Date: Wed, 4 Jul 2018 14:42:01 +0100

Hi Jeffrey,

On 04/07/18 13:30, Jeffrey Brown wrote:
> Composers reuse melodic material across different instruments. I would
> like to do that in Vivid. I would keep a sequence of values and send
> it sometimes to one parameter of one synth, sometimes to a different
> parameter of a different synth.
>
> To do that I would have to coerce those numbers to values of type `I
> a`, where the string `a` is known only at runtime. I tried to write a
> function to do that:
>
>     import GHC.TypeLits
>     toIOf :: (Real n, GHC.TypeLits.KnownSymbol a) => String -> n -> I a
>     toIOf "freq" n = toI n :: I "freq"
>     toIOf "amp" n = toI n :: I "amp"
>
> but it won't compile, because the outputs of `toIOf "freq"` and `toIOf
> "amp"` have different types.

In GHC Haskell the "different types" issue can be partly
solved/worked-around by using RankNTypes with a continuation-passing
style (here the argument 'h' is used at two different types inside 'f',
using Proxy and Typeable just as examples for a simple standalone
program - I'm not familiar with Vivid):

--8<--
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE DataKinds #-}

import Data.Proxy
import Data.Typeable
import GHC.TypeLits

g t = show (typeOf t)

f :: String -> (forall s . KnownSymbol s => Proxy s -> r) -> r
f "freq" h = h (Proxy :: Proxy "freq")
f "amp"  h = h (Proxy :: Proxy "amp" )

main = do
   putStrLn $ f "freq" g
   putStrLn $ f "amp"  g
--8<--

This has the limitation of having to list every possible String/Symbol
pair manually inside f.  The 'reflection' package has a reifySymbol to
make this technique work with arbitrary runtime arguments:
https://hackage.haskell.org/package/reflection-2.1.4/docs/Data-Reflection.html#v:reifySymbol

An approach that might work depending on the "role annotations" of the
'I' type constructor, is to create everything with a dummy Symbol, that
you can pass around with a String representing the desired final name,
and at the last minute use the above technique with Data.Coerce.coerce
to change the Symbol (eg replacing the typeOf in g).  "coerce" is safe
when allowed.


Claude
--
https://mathr.co.uk
_______________________________________________
Livecode mailing list -- livecode_at_we.lurk.org
To unsubscribe send an email to livecode-leave_at_we.lurk.org
Received on Wed Jul 04 2018 - 13:42:23 BST

This archive was generated by hypermail 2.4.0 : Sun Aug 20 2023 - 16:02:23 BST