quickCheckAll always return "True" - unit-testing

I'm trying to use QuickCheck following another answer.
I test like this:
{-# LANGUAGE TemplateHaskell #-}
import Test.QuickCheck
import Test.QuickCheck.All
last' :: [a] -> a
last' [x] = x
last' (_:xs) = last' xs
prop_test x = last' x == last x
check = do
putStrLn "quickCheck"
quickCheck (prop_test :: [Char]-> Bool)
check2 = do
putStrLn "quickCheckAll"
$quickCheckAll
Then I load it in winGHCI and call check and check2. I get
quickCheck
*** Failed! (after 1 test):
Exception:
list.hs:(7,1)-(8,23): Non-exhaustive patterns in function last'
""
which I think it's reasonable. However, I get this from check2
quickCheckAll
True
I'm confused because no matter how I change the last' function, even wrong, quickCheckAll always return True.
What's wrong with my code? How can I fix this?

From the Test.QuickCheck.All docs:
To use quickCheckAll, add a definition to your module along the lines of
return []
runTests = $quickCheckAll
and then execute runTests.
Note: the bizarre return [] in the example above is needed on GHC 7.8; without it, quickCheckAll will not be able to find any of the properties.
Adding return [] before your check makes it work for me.

To use quickCheckAll, you need a function which reads:
return []
runTests = $quickCheckAll
The other comment mentions this, but doesn't point out that it will still always return true unless the function is located below all of your quickCheck functions!

Related

F# If statement type mismatch

i am in a bit of a pickle, i have tried for 2 hours straight trying to get this code to work and im lost.
let DropColumn list =
if List.exists List.isEmpty list then "empty value"
else
list |> List.map List.tail
This gives me an error error FS0001: The type 'string' does not match the type ''a list'
The usual way to deal with failure in functional programming is to use the Result type, which is essentially defined as:
type Result<'T,'TError> =
| Ok of 'T
| Error of 'TError
To apply it to your code we can just wrap the string in the unhappy path with Error and the list from the happy path with Ok:
let DropColumn list =
if List.exists List.isEmpty list then
Error "empty value"
else
list |> List.map List.tail |> Ok
Then to use it you can use pattern matching:
match DropColumn myList with
| Ok newList ->
newList
| Error message ->
printfn "Error occurred: %s" message
[]
The answer given by #glennsl is correct and in many cases the preferred way. However, I'd like to add that there are two other common ways of dealing with invalid input:
Raise an exception. Use this for exceptional cases only, i.e. where you expect your code to halt as the result of invalid data. Do not use it for normal validation where you expect that data can often be wrong.
Use option. This is similar to using Result, but doesn't maintain information for the invalid case. This approach is very common and used a lot in library functions like List.tryFind, List.tryHead etc.
Raise an exception
In the comments you show you already know this option exists, but let's give it here for completeness:
let dropColumnOrRaise list =
if List.exists List.isEmpty list then failwith "empty value"
else
list |> List.map List.tail
Use option
This method usually requires that the business logic that shows an error or does recovery, goes elsewhere.
let tryDropColumn list =
if List.exists List.isEmpty list then None
else
list
|> List.map List.tail
|> Some
Use it as follows:
match tryDropColumn myCols with
| Some columns ->
// do something with valid columns, i.e., display them
printfn "%i columns remaining (List.length (List.head myCols))"
| None ->
// error recovery or showing a message
printfn "No column selected"
When you are dealing with several functions that operate on data that all return option, you can pipe them together with Option.bind (or Option.map if a function doesn't return option).
myCols
|> tryDropColumn
|> Option.map logColumns // function that always succeeds
|> Option.bind tryAtLeastTwoColumns // function that returns None on 1 or 0
|> Option.map showColumns
The code above removes the need to have a match x with for each returned option. Similar code can be used for Result from the previous answer.

Handle Exception: Failure "nth"

In Python, it is quite simple to manage certain error with unit tests. For instance, to verify if a list is emptied or not, I can use assert test != []
Suppose the empty list let test = [];;
try
ignore (nth test 0)
with
Not_found -> print_string("Erreur!");;
Exception: Failure "nth"
I need to raise an error - print_string ("Erreur!") when I encounter Exception: Failure "nth". So far the try/with did not really help me. In Ocaml, is there a workaround to raise the error and print something when I get Exception: Failure "nth"?
In Python, it is quite simple to manage certain error, with unit tests. For instance, to verify if a list is emptied or not, I can use assert test != []
You can do exactly the same (modulo syntax) in OCaml
let require_non_empty xs =
assert (xs <> [])
If you would like to hush an exception and raise in its absence, you can use the match construction, here is how your example could be expressed in OCaml,
let require_empty xs = match List.nth xs 0 with
| exception _ -> ()
| _ -> failwith "the list shall be empty"
In addition, testing frameworks, e.g., OUnit2, provide special functions such as assert_raises for these specific cases.
You seem to be asking whether you can test for specific exceptions. Yes. The exception handling part after with is a list of patterns similar to the match expression.
try
ignore (List.nth [] 0)
with
| Not_found -> ()
| Failure s -> print_string ("Erreur: " ^ s)
| _ -> ()
(It probably isn't wise to depend on the exact string supplied as the argument to Failure. The compiler, in fact, warns you not to do this.)
OCaml also has an asssert expression:
# let list = [] in assert (List.length list > 0);;
Exception: Assert_failure ("//toplevel//", 1, 17).
You can use try/with to handle the resulting exception, of course. The argument to Assert_failure gives the filename, line number, and character number on the line.

OCaml - Creating a function which prompts for floats and returns a list of floats

I'm teaching myself OCaml and I sometimes need to create a function where I'm not really sure what the proper solution should be. Here's one that I'm a little confused about.
I need a function that will prompt the user for individual float values and return everything entered in a float list. I can create this function but I'm not sure if its the proper/best way to do it in Ocaml.
Here's my attempt.
let rec get_floats() =
match
(
try Some(read_float())
with
| float_of_string -> None
)
with
| None -> []
| Some s -> s :: get_floats();;
This code works buts I'm at a loss deciding if its a 'proper OCaml' solution. Note, to exit the function and return the float list just enter a non-integer value.
(I hope that) this is a simple peephole rewrite involving no thought whatsoever of the function in your question:
let rec get_floats() =
try
let f = read_float() in (* as suggested by Martin Jambon *)
f :: (get_floats())
with
| float_of_string -> []
The idea I tried to apply here is that you do not need to convert the success/failure of read_float into an option that you immediately match: just do what you have to do with the value read, and let the with handle the failure case.
Now that I think of it, I should point out that in both your question and my rewrite, float_of_string is a fresh variable. If you meant to match a specific exception, you failed at it: all exception constructors, like datatype constructors, are Capitalized. You might as well have written with _ -> instead of with float_of_string ->, and a recent version of OCaml with all warnings active should tell you that your function (or mine) binds a variable float_of_string without ever using it.
Thanks everyone for the help. This works.
let rec get_floats() =
try
let x = read_float() in
x :: get_floats()
with
| _ -> [];;
List.iter (fun x -> print_endline(string_of_float x)) (get_floats());;

I want to do 2 things after a "then" statement in a "if.. then.. else" statement

let rec filtersList2fromList1 (List1:string list) (List2:string list) : string list =
let finalList = [] in
match List1 with
| s :: tl -> if List.mem s List2 = true
then finalList # [s] else filtersList2fromList1 tl List2
| [] -> []
so that,
filtersList2fromList1 ["x";"y";"z"] ["z";"x"] would be ["x";"z"]
filtersList2fromList1 ["x";"y";"z"] ["x"] would be ["x"]
what I would like to add is, if the "if" statement is true, not only it would execute "finalList # [s]", but also "filtersList2fromList1 tl List2" so that it will be a recursion. Without executing "filtersList2fromList1 tl List2" when it is true,
filtersList2fromList1 ["x";"y";"z"] ["z";"x"] would only be ["x"], which is wrong.
How should I solve this problem?
Thank you very much
To answer your specific question, you'd either use a semi-colon or a let...in construct. In your case, neither will do what you want however.
You should read through the documentation on the standard library, as the List module contains everything you need to do what you want:
let filterList2fromList1 list1 list2 =
List.filter (fun x -> List.mem x list2) list1
Note that since you mentioned recursion, I'm assuming that when you wrote dolls_of you meant filtersList2fromList1. Also I'm assuming that List1 and List2 are supposed to be list1 and list2, since the former would be an error.
It should also be pointed out that # is an O(n) operation and it is not recommended to use it to build up lists. However as Niki pointed out in the comments, your use of finalList is pointless, so you don't actually need # anyway.
To answer your question: You can execute two expressions after another by separating them with a ;. However dolls_of is a function without side effects, so executing it without doing anything with its result would make little sense.
What you actually want to do, as far as I can tell, is:
if List.mem s list2
then s :: filtersList2fromList1 tl list2
else filtersList2fromList1 tl list2

Adding a Show instance to RWH's RandomState example

I have just typed in the RandomState example from real world haskell. It looks like this:
import System.Random
import Control.Monad.State
type RandomState a = State StdGen a
getRandom :: Random a => RandomState a
getRandom =
get >>= \gen ->
let (val, gen') = random gen in
put gen' >>
return val
getTwoRandoms :: Random a => RandomState (a, a)
getTwoRandoms = liftM2 (,) getRandom getRandom
It works, but the result doesn't get displayed. I get the error message:
No instance for (Show (RandomState (Int, Int)))
arising from a use of `print' at <interactive>:1:0-38
Possible fix:
add an instance declaration for (Show (RandomState (Int, Int)))
In a stmt of a 'do' expression: print it
I am having some trouble adding an instance for Show RandomState. Can anyone show me how this is done?
Thanks.
For the sake of being explicit, as jberryman and the comments on the question imply: Something of type RandomState (a, a) is a function, not a value. To do anything with it, you want to run it with an initial state.
I'm guessing you want something like this:
> fmap (runState getTwoRandoms) getStdGen
((809219598,1361755735),767966517 1872071452)
This is essentially what the runTwoRandoms function a bit further in RWH is doing.
Since RandomState is a synonym for State and there isn't an instance of show defined for State, you won't be able to show it.
You would also not be able to derive show because State is just a wrapper for a function and Haskell has no way to define a show for functions that would be useful:
Prelude> show (+)
<interactive>:1:0:
No instance for (Show (a -> a -> a))
arising from a use of `show' at <interactive>:1:0-7
Possible fix: add an instance declaration for (Show (a -> a -> a))
In the expression: show (+)
In the definition of `it': it = show (+)
EDIT: Forgot to add the other piece: GHCi is giving you that error because it uses show behind the scenes on the expressions you enter... REPL and all that.