Thomas thomas
Thomas thomas

Reputation: 795

Pure function with haskell and database access

How can it be possible to tell that a function is pure :

in a data access context ?

Admiting that I have a getAll function that retrieves all the users of a table. This users can vary with time, with add, remove etc...

How can it be possible to make getAll a pure function ?

Upvotes: 1

Views: 828

Answers (1)

epsilonhalbe
epsilonhalbe

Reputation: 15949

Disclaimer: I don't know enough about lisp to give any information about the situation with respect to that language. I only know there is something out there like typed scheme - but again I don't know enough about the power of its type system.

How to tell if a function is pure (in a data access context or not)

In haskell you can see/encode information about the purity of a function in its type signature. I would guess the signature of getAll would be something like:

getAll :: DBConn -> IO Tables

here the IO marks that the impurity of that function. In haskell this modelling of impurity can be done with Monads a general abstraction for situation that appear quite often.

How to make a function pure?

Now there are Monads you can easily get out of - for example Maybe you can use fromMaybe defaultValue maybeValue to get rid of the monad context.

IO is unlike that - there is no safe way to leave the monad context, notably there is unsafePerformIO that can undermine the type system to make the compiler believe "in this situation it is ok to leave IO", but unless you really know what you are doing - do not use this!!!

But maybe this is the wrong question - better ask:

How can I tie pure functions with impure functions together?

Now there are several abstractions that help you tie pure functions in monadic or similar contexts, I recommend to look for Functor, Applicative and (of course) Monad to start with.

For example if you have a function users :: Table -> [User] you could use the Functor abstraction to tie them together

fmap users (getAll conn) (:: IO [User])

or equivalently

users <$> (getAll conn)

note the result of this computation is pure in the users part - and gets the indicator for impurity (nameley IO ..) "inherited" from the getAll conn part.

You can imagine performing the users function inside the IO tag.

Upvotes: 4

Related Questions