Skip to content

Add mapExists function #19

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions src/Data/Exists.purs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
module Data.Exists where

import Prelude

import Unsafe.Coerce (unsafeCoerce)

-- | This type constructor can be used to existentially quantify over a type.
Expand Down Expand Up @@ -31,10 +33,10 @@ type role Exists representational
-- | The `mkExists` function is used to introduce a value of type `Exists f`, by providing a value of
-- | type `f a`, for some type `a` which will be hidden in the existentially-quantified type.
-- |
-- | For example, to create a value of type `Stream Number`, we might use `mkExists` as follows:
-- | For example, to create a value of type `Stream Int`, we might use `mkExists` as follows:
-- |
-- | ```purescript
-- | nats :: Stream Number
-- | nats :: Stream Int
-- | nats = mkExists $ StreamF 0 (\n -> Tuple (n + 1) n)
-- | ```
mkExists :: forall f a. f a -> Exists f
Expand All @@ -55,3 +57,12 @@ mkExists = unsafeCoerce
-- | ```
runExists :: forall f r. (forall a. f a -> r) -> Exists f -> r
runExists = unsafeCoerce

-- | The `mapExists` function is used to convert `Exists f` types to `Exists g` types with `f ~> g`.
-- |
-- | ```purescript
-- | natsShow :: Stream String
-- | natsShow = mapExists (\StreamF s f -> StreamF s $ map show f) $ StreamF 0 (\n -> Tuple (n + 1) n)
-- | ```
mapExists :: forall f g. (f ~> g) -> Exists f -> Exists g
mapExists f = runExists (mkExists <<< f)
9 changes: 7 additions & 2 deletions test/Test/Main.purs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ module Test.Main where

import Prelude

import Data.Exists (Exists, mapExists, mkExists, runExists)
import Effect (Effect)
import Effect.Console (logShow)

import Data.Exists (Exists, mkExists, runExists)

data Tuple a b = Tuple a b

instance Functor (Tuple a) where
map f (Tuple a b) = Tuple a (f b)

snd :: forall a b. Tuple a b -> b
snd (Tuple _ b) = b

Expand Down Expand Up @@ -44,5 +46,8 @@ x = runExists runFooF foo
runFooF :: forall f. FooF f -> Int
runFooF (FooF f fStr) = f fStr

natsShow :: Stream String
natsShow = mapExists (\(StreamF s f) -> StreamF s (map (map show) f)) nats

main :: Effect Unit
main = logShow $ head nats