git.iko.soy/rowtype-yoga/purescript-backend-optimizer
on main help sign in
70 lines 2.1 kB history raw
1-- @inline export mapU arity=1
2-- @inline export filterMapU arity=1
3-- @inline export filterU arity=1
4-- @inline export fromArray arity=1
5-- @inline export toArray arity=1
6-- @inline export overArray arity=1
7module Snapshot.Fusion02 (test) where
9import Prelude
11import Data.Array as Array
12import Data.Exists (Exists, mkExists, runExists)
13import Data.List as List
14import Data.Maybe (Maybe(..))
15import Data.String as String
16import Partial.Unsafe (unsafePartial)
18type Step a s = forall r. (Unit -> r) -> (s -> a -> r) -> r
19data Unfold' a s = Unfold s (s -> Step a s)
20type Unfold a = Exists (Unfold' a)
22mapU :: forall a b. (a -> b) -> Unfold a -> Unfold b
23mapU f = runExists \(Unfold s1 step) ->
24 mkExists $ Unfold s1 \s2 nothing just ->
25 step s2 nothing \s3 a ->
26 just s3 (f a)
28filterMapU :: forall a b. (a -> Maybe b) -> Unfold a -> Unfold b
29filterMapU f = runExists \(Unfold s1 step) ->
30 mkExists $ Unfold s1 \s2 nothing just -> do
31 let
32 loop s3 =
33 step s3 nothing \s4 a ->
34 case f a of
35 Nothing ->
36 loop s4
37 Just b ->
38 just s4 b
39 loop s2
41filterU :: forall a. (a -> Boolean) -> Unfold a -> Unfold a
42filterU p = filterMapU \a -> if p a then Just a else Nothing
44fromArray :: forall a. Array a -> Unfold a
45fromArray arr = mkExists $ Unfold 0 \ix nothing just ->
46 if ix == Array.length arr then
47 nothing unit
48 else
49 just (ix + 1) (unsafePartial Array.unsafeIndex arr ix)
51toArray :: forall a. Unfold a -> Array a
52toArray = runExists \(Unfold s1 step) -> do
53 let
54 loop s2 acc =
55 step s2
56 (\_ -> Array.reverse (List.toUnfoldable acc))
57 (\s3 a -> loop s3 (List.Cons a acc))
58 loop s1 List.Nil
60overArray :: forall a b. (Unfold a -> Unfold b) -> Array a -> Array b
61overArray unfold = toArray <<< unfold <<< fromArray
63test :: Array Int -> Array String
64test = overArray do
65 mapU (add 1)
66 >>> mapU show
67 >>> filterMapU (String.stripPrefix (String.Pattern "1"))
68 >>> mapU (append "2")
69 >>> filterU (_ /= "wat")
70 >>> mapU (flip append "1")