[Haskell-cafe] a monad for secret information
David Roundy
droundy at darcs.net
Tue Oct 10 12:25:47 EDT 2006
On Mon, Oct 09, 2006 at 11:06:35PM -0400, Seth Gordon wrote:
> I finally (think I) understand monads well enough to make one up:
[...]
> The not-so-nice thing is that the literal text of the password is baked
> into the data definition. I'd like to have a more general version of
> Secret that allows someone to pass the password in when constructing a
> secret, and preserves that password when "return" is used, but doesn't
> let the second argument of (>>=) see the password. Something like this:...
> >data Classification pw a = Classification pw a
> >declassify (Classification pw a) pw' = case pw' of
> > pw -> Just a
> > _ -> Nothing
> >
> >type Secret = Classification "xyzzy"
Try
>module Secret (Secret, classify, declassify)
>where
>
>data Secret a = Secret String a
>
>classify :: String -> a -> Secret a
>classify pw x = Secret pw x
>
>declassify :: Secret a -> String -> Maybe a
>declassify (Secret pw x) pw' | pw' == pw = Just x
>declassify (Secret _ _) _ = Nothing
>
>instance Monad Secret where
> return = classify ""
> (Secret pw x) >>= f = case f x of
> Secret _ y -> Secret pw y
Now return itself doesn't assign a password, but you can classify something
manually, and then perform computations on that data in a safe manner.
It's just as safe as your code, because the constructor of secret is hidden
which hides the password just as well as the data.
Of course, this is run-time checking, and you'd be safer with a phantom
type-level password which is statically verified, which is also doable, but
not so easily. It wouldn't be very hard either, though. It also wouldn't
be Haskell 98.
David
More information about the Haskell-Cafe
mailing list