Getting error description from compiling regexp - regex

I am trying to compile a regexp and get an error message that can be presented to the user. I tried this with Text.Regex.TDFA and Text.Regex.Posix and it seems to behave the same:
Prelude Text.Regex.TDFA Data.Maybe Data.Either.Utils> fromLeft $ (makeRegexM ".[" :: Either String Regex)
"*** Exception: parseRegex for Text.Regex.TDFA.String failed:".[" (line 1, column 3):
unexpected end of input
expecting "^", "]", "-" or Failed to parse bracketed string
Prelude Text.Regex.TDFA Data.Maybe Data.Either.Utils> isJust $ (makeRegexM ".[" :: Maybe Regex)
False
Prelude Text.Regex.TDFA Data.Maybe Data.Either.Utils> isJust $ (makeRegexM "." :: Maybe Regex)
True
The Maybe monad seems to work; the Either does not. However the documentation says, it should use 'fail' - which, as far as I know, is defined in Either monad. Am I doing something wrong?

The reason probably is that the monad instance for Either e recently changed. In mtl-1.*, there used to be an
instance Error e => Monad (Either e) where
...
fail msg = Left (strMsg msg) -- I may misremember the exact names
so calling fail there didn't cause an exception. Now, there is a monad instance in base (Control.Monad.Instances)
instance Monad (Either e) where
...
fail s = error s -- implicitly from the default method for fail
so you get the above.

Related

SML getting an unbound variable or constructor error when everything seems right

I'm trying to figure out mutual recursion. I have this code:
fun take(L)=
if L=nil then nil
else hd(L) :: skip(tl(L))
AND
fun skip(L)=
if L=nil then nil
else take(tl(L));
but it gives me these errors:
stdIn:54.14-54.18 Error: unbound variable or constructor: skip
stdIn:55.1-55.4 Error: unbound variable or constructor: AND
What am I doing wrong?
Your immediate error is because Standard ML is case-sensitive, and all of its reserved words are in lowercase; so you need to write and rather than AND.
Additionally, fun introduces an entire declaration, not an individual binding, meaning that you need to remove the extra fun after and.
Lastly, your functions currently require the list to have an equality type (such as int list or string list), which may not be a deal-breaker, but given what the functions actually do, there's really no reason they can't support non-equality types such as real list. To achieve that, you should match the parameter against the pattern nil, instead of testing whether the parameter equals nil. (More generally, you should use pattern-matching in more places; you have no reason to call hd and tl.)
Putting it together:
fun take nil = nil
| take (h::t) = h :: skip t
and skip nil = nil
| skip (h::t) = take t

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.

How can I unit test Alex code?

I'm writing a lexer in Alex with the monad wrapper. It's not behaving as I expect, and I would like to write some unit tests for it. I can write unit tests for lexing a single token by doing:
runAlex "foo" alexMonadScan `shouldBe` Right TokenFoo
but I don't know how to test that the string "foo bar" gets lexed to [TokenFoo, TokenBar].
Given that Token is my token type, I'd need a function like runAlex that has the type String -> Alex [Token] -> Either String [Token], but I don't know how to transform alexMonadScan so that it has the type Alex [Token] rather than Alex Token.
I tried
runAlex "foo bar" (liftM (:[]) alexMonadScan) `shouldBe` [TokenFoo, TokenBar]
which seems to have the right type, but it returns Right [TokenEOF], apparently dropping the tokens it saw along the way.
How can I achieve this?
There is a function alexScanTokens :: String -> [token] which you can use.
It's defined in the file templates/wrappers.hs
Here's a monadic version I found here:
alexScanTokens :: String -> Either String [Keyword]
alexScanTokens inp = runAlex inp gather
where
gather = do
t <- alexMonadScan
case trace (show t) t of
EOF -> return [EOF]
_ -> (t:) `liftM` gather

quickCheckAll always return "True"

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!

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.