How does one use monadic properties in SmallCheck? - testing

I would like to write a SmallCheck property that uses IO, but I can't figure out how I am supposed to do it. Specifically, the goal is to write a property that is an instance of Testable IO Bool so that I can feed it into smallCheck (or testProperty in test-framework). Unfortunately, the best I can come up with is the following:
smallCheck 5 (\(x :: Int) → return True :: IO Bool)
This doesn't work because it is an instance of Testable IO (IO Bool) rather than Testable IO Bool, but I can't figure out how to rewrite it so that it works.
Any help would be appreciated.

You want the monadic combinator. It takes an arbitrary monad m and wraps it into a Property that is an instance of Testable.
smallCheck 5 $ \(x :: Int) -> monadic $ (return True :: IO Bool)

It turns out that there is a function that does exactly what I wanted:
monadic :: Testable m a => m a -> Property m
You use it like so:
smallCheck 5 $ \(x :: Int) → monadic (putStrLn (show x) >> return True)
Specifically, note how monadic needs to be nested after the function argument.

Related

Partial application of Printf.ksprintf

I'm trying to write a version of Printf.printf that always appends a newline character after writing its formatted output. My first attempt was
# let say fmt = Printf.ksprintf print_endline fmt;;
val say : ('a, unit, string, unit) format4 -> 'a = <fun>
The type signature looks right and say works as expected. I noticed that fmt is listed twice, and thought that partial application could eliminate it. So I tried this instead:
# let say = Printf.ksprintf print_endline;;
val say : ('_weak1, unit, string, unit) format4 -> '_weak1 = <fun>
The function definition looks cleaner, but the type signature looks wrong and say no longer works as expected. For example, say doesn't type check if the format string needs a variable number of arguments: I get an error that say "is applied to too many arguments".
I can use the let say fmt = … implementation, but why doesn't partial application work?
OCaml's type-checker loses polymorphism during partial application. That is, when you partially apply a function, the resulting function is no longer polymorphic. That's why you see '_weak1 in the second type signature.
When you include the fmt argument, you help the type-checker recognize that polymorphism is still present.
This process is called "eta conversion." Removing your fmt argument is "eta reduction" and adding it back in is called "eta expansion." You may encounter that terminology when working with other functional programming languages.
This is the value restriction at work: https://ocaml.org/manual/polymorphism.html#s:weak-polymorphism . In brief, only syntactic values can be safely generalized in let-binding in presence of mutable variables in the language.
In particular,
let f = fun x -> g y x
is a syntactic value that can be generalized, whereas
let f = g y
is a computation that cannot (always) be generalized.
A example works quite well to illustrate the issue, consider:
let fake_pair x =
let store = ref None in
fun y ->
match !store with
| None ->
store := Some y;
x, y
| Some s ->
x, s
then the type of fake_pair is 'a -> 'b -> 'a * 'b.
However, once partially applied
let p = fake_pair 0
we have initialized the store mutable value, and it is important that all subsequent call to p share the same type (because they must match the stored value). Thus the type of p is '_weak1 -> int * '_weak1 where '_weak1 is a weak type variable, aka a temporary placeholder for a concrete type.

RecursiveDo in Idris? (Using value before it is defined while in do notation)

Does Idris 2 have anything similar to Haskell's RecursiveDo. I have certain values that I would like to use before they are defined while in the IO monad. I am trying to build a cyclical FRP network. They implement the following interface:
interface Loop (a : Type) where
loop : (a -> IO (b, a)) -> IO b
However using loop is ugly. Is there a better way?

List of types from a function type

I would like to make a function that given a function type (e.g. String -> Nat -> Bool), would return a list of types corresponding to that function type (e.g. [String, Nat, Bool]). Presumably the signature of such a function would be Type -> List Type, but I am struggling to determine how it would be implemented.
I don't believe it could be done in general, because you cannot patter-match on functions. Neither can you check for the type of a function. That is not what dependent types are about. Just like in Haskell or OCaml the only thing you can actually do with a function is apply it to some argument. However, I devised some trick which might do:
myFun : {a, b : Type} -> (a -> b) -> List Type
myFun {a} {b} _ = [a, b]
Now the problem is that a -> b is the only signature that would match any arbitrary function. But, of course it does not behave the way you'd like for functions with arity higher than one:
> myFun (+)
[Integer, Integer -> Integer] : List Type
So some sort of recursive call to itself would be necessary to extract more argument types:
myFun : {a, b : Type} -> (a -> b) -> List Type
myFun {a} {b} _ = a :: myFun b
The problem here is that b is an arbitrary type, not necessarily a function type and there is no way I can figure out to dynamically check whether it is a function or not, so I suppose this is as much as you can do with Idris.
However, dynamic checking for types (at least in my opinion) is not a feature to be desired in a statically typed language. After all the whole point of static typing is to specify in advance what kind of arguments a function can handle and prevent calling functions with invalid arguments at compile time. So basically you probably don't really need it at all. If you specified what you grander goal was, someone would likely have shown you the right way of doing it.

How does Haskell deal with documentation?

How do I get online documentation in Haskell?
Are there anything as elegant/handy as what Python does below?
>>> help([].count)
Help on built-in function count:
count(...)
L.count(value) -> integer -- return number of occurrences of value
Interactive help in GHCi
The standard Haskell REPL is GHCi. While it is not possible to access complete documentation from within GHCi, it is possible to get quite a lot of useful info.
Print types. In 90% of cases this is enough to understand what a function does and how to use it.
ghci> :t zipWith
zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
:t is short for :type.
Print information about symbols. This is useful to find what module does a symbol belong. For a data type it allows to see its definition and class instances. For a type class it allows to see its interface and a list of types which are its instances.
ghci> :i Bool
data Bool = False | True -- Defined in GHC.Bool
instance Bounded Bool -- Defined in GHC.Enum
instance Enum Bool -- Defined in GHC.Enum
instance Eq Bool -- Defined in GHC.Base
instance Ord Bool -- Defined in GHC.Base
instance Read Bool -- Defined in GHC.Read
instance Show Bool -- Defined in GHC.Show
ghci> :i Eq
class Eq a where
(==) :: a -> a -> Bool
(/=) :: a -> a -> Bool
-- Defined in GHC.Classes
instance (Eq a) => Eq (Maybe a) -- Defined in Data.Maybe
instance (Eq a, Eq b) => Eq (Either a b) -- Defined in Data.Either
(many more instances follow)
ghci> :i zipWith
zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
-- Defined in GHC.List
:i is short for :info.
Print kinds. Use :k on type constructors.
ghci> :k Maybe
Maybe :: * -> *
ghci> :k Int
Int :: *
:k is short for :kind.
Browse module's contents. This allows to see what symbols an imported module offers.
ghci> :browse Data.List
(\\) :: (Eq a) => [a] -> [a] -> [a]
delete :: (Eq a) => a -> [a] -> [a]
deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a]
...
(many lines follow)
:t, :k and :i work only for symbols in scope (you need to import module with :m + Module.Name first). :browse works for all available modules.
Online documentation
Most Haskell libraries are documented with Haddock. You can open an HTML version of the documentation and read the details.
You can install it locally, if you use --enable-documentation flag in cabal install.
Otherwise, a good point to browse through all the documentation is a package list on Hackage. It allows to see the documentation also for earlier versions of any package. Sometimes it is very useful.
Currently, there is no way to view the Haddock documentation within ghci, but there is a ticket for it.
You can however get a small bit of info using the :info command, e.g.
ghci> :i nub
nub :: (Eq a) => [a] -> [a] -- Defined in Data.List
so that you at least know where to look for the documentation for a particular function.
You can use Hoogle to search for documentation by function name or its type signature (perhaps, approximate type signature). There's also a command-line offline version of this tool which you can get from hackage.

How to mock for testing in Haskell?

Suppose I am defining a Haskell function f (either pure or an action) and somewhere within f I call function g. For example:
f = ...
g someParms
...
How do I replace function g with a mock version for unit testing?
If I were working in Java, g would be a method on class SomeServiceImpl that implements interface SomeService. Then, I'd use dependency injection to tell f to either use SomeServiceImpl or MockSomeServiceImpl. I'm not sure how to do this in Haskell.
Is the best way to do it to introduce a type class SomeService:
class SomeService a where
g :: a -> typeOfSomeParms -> gReturnType
data SomeServiceImpl = SomeServiceImpl
data MockSomeServiceImpl = MockSomeServiceImpl
instance SomeService SomeServiceImpl where
g _ someParms = ... -- real implementation of g
instance SomeService MockSomeServiceImpl where
g _ someParms = ... -- mock implementation of g
Then, redefine f as follows:
f someService ... = ...
g someService someParms
...
It seems like this would work, but I'm just learning Haskell and wondering if this is the best way to do this? More generally, I like the idea of dependency injection not just for mocking, but also to make code more customizable and reusable. Generally, I like the idea of not being locked into a single implementation for any of the services that a piece of code uses. Would it be considered a good idea to use the above trick extensively in code to get the benefits of dependency injection?
EDIT:
Let's take this one step further. Suppose I have a series of functions a, b, c, d, e, and f in a module that all need to be able to reference functions g, h, i, and j from a different module. And suppose I want to be able to mock functions g, h, i, and j. I could clearly pass the 4 functions in as parameters to a-f, but that's a bit of a pain to add the 4 parameters to all the functions. Plus, if I ever needed to change the implementation of any of a-f to call yet another method, I'd need to change its signature, which could create a nasty refactoring exercise.
Any tricks to making this type of situation work easily? For example, in Java, I could construct an object with all of its external services. The constructor would store the services off in member variables. Then, any of the methods could access those services via the member variables. So, as methods are added to services, none of the method signatures change. And if new services are needed, only the constructor method signature changes.
Why use unit testing when you can have Automated Specification-Based Testing? The QuickCheck library does this for you. It can generate arbitrary (mock) functions and data using the Arbitrary type-class.
"Dependency Injection" is a degenerate form of implicit parameter passing. In Haskell, you can use Reader, or Free to achieve the same thing in a more Haskelly way.
Another alternative:
{-# LANGUAGE FlexibleContexts, RankNTypes #-}
import Control.Monad.RWS
data (Monad m) => ServiceImplementation m = ServiceImplementation
{ serviceHello :: m ()
, serviceGetLine :: m String
, servicePutLine :: String -> m ()
}
serviceHelloBase :: (Monad m) => ServiceImplementation m -> m ()
serviceHelloBase impl = do
name <- serviceGetLine impl
servicePutLine impl $ "Hello, " ++ name
realImpl :: ServiceImplementation IO
realImpl = ServiceImplementation
{ serviceHello = serviceHelloBase realImpl
, serviceGetLine = getLine
, servicePutLine = putStrLn
}
mockImpl :: (Monad m, MonadReader String m, MonadWriter String m) =>
ServiceImplementation m
mockImpl = ServiceImplementation
{ serviceHello = serviceHelloBase mockImpl
, serviceGetLine = ask
, servicePutLine = tell
}
main = serviceHello realImpl
test = case runRWS (serviceHello mockImpl) "Dave" () of
(_, _, "Hello, Dave") -> True; _ -> False
This is actually one of the many ways to create OO-styled code in Haskell.
To follow up on the edit asking about multiple functions, one option is to just put them in a record type and pass the record in. Then you can add new ones just by updating the record type. For example:
data FunctionGroup t = FunctionGroup { g :: Int -> Int, h :: t -> Int }
a grp ... = ... g grp someThing ... h grp someThingElse ...
Another option that might be viable in some cases is to use type classes. For example:
class HasFunctionGroup t where
g :: Int -> t
h :: t -> Int
a :: HasFunctionGroup t => <some type involving t>
a ... = ... g someThing ... h someThingElse
This only works if you can find a type (or multiple types if you use multi-parameter type classes) that the functions have in common, but in cases where it is appropriate it will give you nice idiomatic Haskell.
Couldn't you just pass a function named g to f? As long as g satisfies the interface typeOfSomeParms -> gReturnType, then you should be able to pass in the real function or a mock function.
eg
f g = do
...
g someParams
...
I have not used dependency injection in Java myself, but the texts I have read made it sound a lot like passing higher-order functions, so maybe this will do what you want.
Response to edit: ephemient's answer is better if you need to solve the problem in an enterprisey way, because you define a type containing multiple functions. The prototyping way I propose would just pass a tuple of functions without defining a containing type. But then I hardly ever write type annotations, so refactoring that is not very hard.
A simple solution would be to change your
f x = ...
to
f2 g x = ...
and then
f = f2 g
ftest = f2 gtest
If the functions you depend on are in another module then you could play games with visible module configurations so that either the real module or a mock module is imported.
However I'd like to ask why you feel the need to use mock functions for unit testing anyway. You simply want to demonstrate that the module you are working on does its job. So first prove that your lower level module (the one you want to mock) works, and then build your new module on top of it and demonstrate that works too.
Of course this assumes that you aren't working with monadic values, so it doesn't matter what gets called or with what parameters. In that case you probably need to demonstrate that the right side effects are being invoked at the right time, so monitoring what gets called when is necessary.
Or are you just working to a corporate standard that demands that unit tests only exercise a single module with the whole rest of the system being mocked? That is a very poor way of testing. Far better to build your modules from the bottom up, demonstrating at each level that the modules meet their specs before proceeding to the next level. Quickcheck is your friend here.
You could just have your two function implementations with different names, and g would be a variable that is either defined to be one or the other as you need.
g :: typeOfSomeParms -> gReturnType
g = g_mock -- change this to "g_real" when you need to
g_mock someParms = ... -- mock implementation of g
g_real someParms = ... -- real implementation of g