Skip to content

Commit 6b6118d

Browse files
committed
typed-protocols: added AnyMessageAndAgency pattern synonym
1 parent 03270e4 commit 6b6118d

File tree

1 file changed

+25
-0
lines changed
  • typed-protocols/src/Network/TypedProtocol

1 file changed

+25
-0
lines changed

typed-protocols/src/Network/TypedProtocol/Codec.hs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
{-# LANGUAGE FlexibleInstances #-}
44
{-# LANGUAGE GADTs #-}
55
{-# LANGUAGE NamedFieldPuns #-}
6+
{-# LANGUAGE PatternSynonyms #-}
67
{-# LANGUAGE PolyKinds #-}
78
{-# LANGUAGE QuantifiedConstraints #-}
89
{-# LANGUAGE RankNTypes #-}
@@ -14,6 +15,7 @@
1415
-- @UndecidableInstances@ extension is required for defining @Show@ instance of
1516
-- @'AnyMessage'@ and @'AnyMessage'@.
1617
{-# LANGUAGE UndecidableInstances #-}
18+
{-# LANGUAGE ViewPatterns #-}
1719

1820
module Network.TypedProtocol.Codec
1921
( -- * Defining and using Codecs
@@ -36,6 +38,7 @@ module Network.TypedProtocol.Codec
3638
, runDecoderPure
3739
-- ** Codec properties
3840
, AnyMessage (..)
41+
, pattern AnyMessageAndAgency
3942
, prop_codecM
4043
, prop_codec
4144
, prop_codec_splitsM
@@ -301,12 +304,34 @@ data AnyMessage ps where
301304
=> Message ps (st :: ps) (st' :: ps)
302305
-> AnyMessage ps
303306

307+
304308
-- requires @UndecidableInstances@ and @QuantifiedConstraints@.
305309
instance (forall (st :: ps) (st' :: ps). Show (Message ps st st'))
306310
=> Show (AnyMessage ps) where
307311
show (AnyMessage (msg :: Message ps st st')) =
308312
"AnyMessage " ++ show msg
309313

314+
315+
-- | A convenient pattern synonym which unwrap 'AnyMessage' giving both the
316+
-- singleton for the state and the message.
317+
--
318+
pattern AnyMessageAndAgency :: forall ps. ()
319+
=> forall (st :: ps) (st' :: ps).
320+
(SingI st, ActiveState st)
321+
=> Sing st
322+
-> Message ps st st'
323+
-> AnyMessage ps
324+
pattern AnyMessageAndAgency sing msg <- AnyMessage (getAgency -> (msg, sing))
325+
where
326+
AnyMessageAndAgency _ msg = AnyMessage msg
327+
{-# COMPLETE AnyMessageAndAgency #-}
328+
329+
-- | Internal view pattern for 'AnyMessageAndAgency'
330+
--
331+
getAgency :: SingI st => Message ps st st' -> (Message ps st st', Sing st)
332+
getAgency msg = (msg, sing)
333+
334+
310335
-- | The 'Codec' round-trip property: decode after encode gives the same
311336
-- message. Every codec must satisfy this property.
312337
--

0 commit comments

Comments
 (0)