typed-encoding- Type safe string transformations

Safe HaskellSafe




Examples about how to work with encoded data. This topic is (an interesting) work-in-progress.

Modifying encoded data would typically corrupt the encoding. Current approach is to use Unsafe wrapping class that exposes Functor and (limited) Applicative and Monad instances.



>>> :set -XOverloadedStrings -XMultiParamTypeClasses -XDataKinds

exAsciiTE :: Either EncodeEx (Enc '["r-ASCII"] () Text) Source #

Starting example

exAsciiT :: Enc '["r-ASCII"] () Text Source #

with either removed

Safe and Slow approach

modifiedAsciiT :: Either RecreateEx (Enc '["r-ASCII"] () Text) Source #

recreateFAll is the way to recover encoding in a safe way

>>> let payload = getPayload exAsciiT
>>> let newPayload = payload <> " some extra stuff"
>>> recreateFAll . toEncoding () $ newPayload :: Either RecreateEx (Enc '["r-ASCII"] () T.Text)
Right (UnsafeMkEnc Proxy () "HELLO some extra stuff")

Alternatively, UncheckedEnc type can be used in recreation, see Overview

Unsafe but fast

toLowerAscii :: Either EncodeEx (Enc '["r-ASCII"] () Text) Source #

The issue with recreateFAll is that it may be expensive.

This apprach uses Unsafe to perform (in general risky) operation on the internal payload.

>>> exAsciiTE
Right (UnsafeMkEnc Proxy () "HELLO")
>>> exAsciiTE >>= pure . Unsafe.withUnsafe (fmap T.toLower)
Right (UnsafeMkEnc Proxy () "hello")

Example uses of toLower within encoded data this operation is safe for ASCII restriction but Enc '["r-ASCII"] () T.Text does not expose it We use Functor instance of Unsafe wrapper type to accomplish this

appendAscii :: Either EncodeEx (Enc '["r-ASCII"] () Text) Source #

Similar example uses applicative instance of Unsafe

>>> let Right hELLO = exAsciiTE
>>> let Right hello = toLowerAscii
>>> displ $ Unsafe.runUnsafe ((<>) <$> Unsafe.Unsafe hELLO <*> Unsafe.Unsafe hello)
"Enc '[r-ASCII] () (Text HELLOhello)"