Cannot reproduce simple example form the Hood (Haskell Object Observation Debugger) package documentation - haskell

To get some more insight into the intermediate steps involved in the evaluation of expressions, I would like to give the hood (http://hackage.haskell.org/package/hood) package a try.
On the home page (http://ku-fpg.github.io/software/hood/) of the package, there are some examples of the capabilities of hood, namely this example:
import Debug.Hood.Observe
ex2 = print
. reverse
. (observe "intermediate")
. reverse
$ [1..9]
n = runO ex2
When I try to run this example I get the following error:
hoodTests.hs:10:10: error:
• Ambiguous type variable ‘a0’ arising from the literal ‘1’
prevents the constraint ‘(Num a0)’ from being solved.
Probable fix: use a type annotation to specify what ‘a0’ should be.
These potential instances exist:
instance Num Integer -- Defined in ‘GHC.Num’
instance Num Double -- Defined in ‘GHC.Float’
instance Num Float -- Defined in ‘GHC.Float’
...plus two others
(use -fprint-potential-instances to see them all)
• In the expression: 1
In the second argument of ‘($)’, namely ‘[1 .. 9]’
In the expression:
print . reverse . (observe "intermediate") . reverse $ [1 .. 9] Failed, modules loaded: none.
I guess this means that [1..9] should have a clear Type like Int or Float.
Then I change the script like this:
import Debug.Hood.Observe
al :: [Int]
al = [0..9]
ex2 = print
. reverse
. (observe "intermediate")
. reverse
$ al
n = runO ex2
Now the error is gone, but the output is not as expected. Instead of
[0,1,2,3,4,5,6,7,8,9]
-- intermediate
9 : 8 : 7 : 6 : 5 : 4 : 3 : 2 : 1 : 0 : []
the output is
*Main> n
[0,1,2,3,4,5,6,7,8,9]
*Main>
The package is old I think, it was last updated for ghc-6.x and I use ghc-8. Is this the reason that it does not work or am I missing something else?

Related

Function length "a" does not compile, if OverloadedStrings extension is enabled

If "{-# LANGUAGE OverloadedStrings #-}" is included at the top of the source file, or in package.yaml (I am using stack), then
length "a" -- does not compile anymore.
However the custom function length' is working fine
length' :: [a] -> Int
length' xs = sum [1 | _ <- xs]
The package Data.String is imported - I think the problem is there, but, I am interested to see, if somebody had similar problem.
Stack and GHC versions:
Version 2.3.1, Git revision x86_64 hpack-0.33.0, ghc-8.8.3
I am using mac osx, but the same error is in Linux and windows too.
This is an error produced by stack:
/Users/admin1/Haskell/PROJECTS/orig1/src/Lib.hs:13:29: error:
• Ambiguous type variables ‘t0’,
‘a0’ arising from the literal ‘"a"’
prevents the constraint ‘(IsString (t0 a0))’ from being solved.
Probable fix: use a type annotation to specify what ‘t0’,
‘a0’ should be.
These potential instances exist:
instance (a ~ Char) => IsString [a] -- Defined in ‘Data.String’
...plus two instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In the first argument of ‘length’, namely ‘"a"’
In the first argument of ‘show’, namely ‘(length "a")’
In the second argument of ‘($)’, namely ‘show (length "a")’
|
13 | putStrLn $ show (length "a") -- does not work, if "- OverloadedStrings" is on
This is because length has a signature length :: Foldable f => f a -> Int, so it can be any Foldable type. If you use the OverloadedStrings extension, then "foo" is no longer a String, it can be any type IsString a => a, and multiple fo these can be Foldable f => f as as well.
What you can do is give the compiler a type hint, for example with:
length ("a" :: String)

why does quickCheck create lists of units

I tried the following from the paper QuickCheck Testing for fun and profit.
prop_revApp xs ys = reverse (xs ++ ys) == reverse xs ++ reverse ys
and it passed even though it should not have.
I ran verboseCheck and I see that it is only checking lists of units, i.e.:
Passed:
[(),(),(),(),(),(),(),(),(),(),(),(),(),()]
I was wondering why this was.
I am aware I can fix it by defining the type of the property but was wondering if this was necessary or I was missing something.
The prop_revApp function is quite generic:
*Main> :t prop_revApp
prop_revApp :: Eq a => [a] -> [a] -> Bool
If you're just loading the code in GHCi, and run it, yes, indeed, the property passes:
*Main> quickCheck prop_revApp
+++ OK, passed 100 tests.
This is because GHCi comes with a set of preferred defaults. For convenience, it'll try to use the simplest type it can.
It doesn't get much simpler than (), and since () has an Eq instance, it picks that.
If, on the other hand, you actually try to write and compile some properties, the code doesn't compile:
import Test.Framework (defaultMain, testGroup)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.QuickCheck
main :: IO ()
main = defaultMain tests
prop_revApp xs ys = reverse (xs ++ ys) == reverse xs ++ reverse ys
tests = [
testGroup "Example" [
testProperty "prop_revApp" prop_revApp
]
]
If you try to run these tests with stack test, you'll get a compiler error:
test\Spec.hs:11:17: error:
* Ambiguous type variable `a0' arising from a use of `testProperty'
prevents the constraint `(Arbitrary a0)' from being solved.
Probable fix: use a type annotation to specify what `a0' should be.
These potential instances exist:
instance (Arbitrary a, Arbitrary b) => Arbitrary (Either a b)
-- Defined in `Test.QuickCheck.Arbitrary'
instance Arbitrary Ordering
-- Defined in `Test.QuickCheck.Arbitrary'
instance Arbitrary Integer
-- Defined in `Test.QuickCheck.Arbitrary'
...plus 19 others
...plus 61 instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
* In the expression: testProperty "prop_revApp" prop_revApp
In the second argument of `testGroup', namely
`[testProperty "prop_revApp" prop_revApp]'
In the expression:
testGroup "Example" [testProperty "prop_revApp" prop_revApp]
|
11 | testProperty "prop_revApp" prop_revApp
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
You'll have to give the property a more specific type; e.g.
tests = [
testGroup "Example" [
testProperty "prop_revApp" (prop_revApp :: [Int] -> [Int] -> Bool)
]
]
Now the test compiles, but fails:
$ stack test
Q56101904-0.1.0.0: test (suite: Q56101904-test)
Example:
prop_revApp: [Failed]
*** Failed! Falsifiable (after 3 tests and 3 shrinks):
[1]
[0]
(used seed -7398729956129639050)
Properties Total
Passed 0 0
Failed 1 1
Total 1 1
Q56101904-0.1.0.0: Test suite Q56101904-test failed
Test suite failure for package Q56101904-0.1.0.0
Q56101904-test: exited with: ExitFailure 1
Logs printed to console

Ambigous type variable that prevents the constraint

I am fiddling around with IO and i do not understand the following error :
* Ambiguous type variable `a0' arising from a use of `readLine'
prevents the constraint `(Console a0)' from being solved.
Probable fix: use a type annotation to specify what `a0' should be.
These potential instance exist:
instance Console Int -- Defined at Tclass.hs:8:14
* In the second argument of `(+)', namely `readLine'
In the second argument of `($)', namely `(2 + readLine)'
In the expression: putStrLn . show $ (2 + readLine)
|
17 | useInt =putStrLn . show $ (2+readLine)
Code
module Tclass where
import System.Environment
class Console a where
writeLine::a->IO()
readLine::IO a
instance Console Int where
writeLine= putStrLn . show
readLine = do
a <- getLine
let b= (read a)::Int
return b
useInt::IO()
useInt =putStrLn . show $ (2+readLine)
P.S i do not understand shouldn't the compiler infer the type of the instance for readLine and make the addition with 2 in the useInt method ?
2 is not only an Int in Haskell but it is of any numeric type, including Float,Double,Integer,.... Its type is Num a => a -- a polymorphic type fitting each numeric type.
So, you could use (2::Int) instead. Then you'll discover that (2::Int) + readLine is a type error, since readLine :: Int is wrong, we only get readLine :: IO Int.
You can try this, instead
useInt :: IO ()
useInt = do
i <- readLine
putStrLn . show (2 + i :: Int)

Write Quick Sort in Haskell and need help to resolve the issue

I try to write a quick sort in Haskell and I knew there are many versions out there.
This one is pretty simple for Int type
quickSort1::[Int]->[Int]
quickSort1 [] = []
quickSort1 (x:xs) = [l | l <- xs, l < x] ++ [x] ++ [ r | r <- xs, r > x]
I can print on Main as following
print $ quickSort1 [] -- output []
print $ quickSort1 [2, 1] -- output [1, 2]
I modified the above quickSort1 to "more general" type with (Ord a) instead of Int
quickSort2::(Ord a)=>[a]->Maybe [a]
quickSort2 [] = Nothing
quickSort2 (x:xs) = Just $ [ l | l <- xs, l < x] ++ [x] ++ [ r | r <- xs, r > x]
On my Main, I can run
it works
print $ quickSort2 [2, 1] -- output [1, 2]
I got compiler error when I run following
print $ quickSort2 [] -- got error
Can anyone explain to me what is going on with my new version of quickSort2
I assume you use a file foo.hs and in it
main = print $ quicksort []
quicksort = ... - as defined above in quickSort2
then you get two error messages when you runghc foo.hs
foo.hs:3:8: error:
• Ambiguous type variable ‘a0’ arising from a use of ‘print’
prevents the constraint ‘(Show a0)’ from being solved.
Probable fix: use a type annotation to specify what ‘a0’ should be.
These potential instances exist:
instance Show Ordering -- Defined in ‘GHC.Show’
instance Show Integer -- Defined in ‘GHC.Show’
instance Show a => Show (Maybe a) -- Defined in ‘GHC.Show’
...plus 22 others
...plus 11 instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In the expression: print $ quicksort []
In an equation for ‘main’: main = print $ quicksort []
one telling you that ghc cannot tell what Show instance to use and ghc 8 already tells you how to solve this:
add a type annotation (as #duplode already suggested)
main = print $ quicksort ([] :: [Int])
Quite similar but slightly different is the second error message
foo.hs:3:16: error:
• Ambiguous type variable ‘a0’ arising from a use of ‘quicksort’
prevents the constraint ‘(Ord a0)’ from being solved.
Probable fix: use a type annotation to specify what ‘a0’ should be.
These potential instances exist:
instance Ord Ordering -- Defined in ‘GHC.Classes’
instance Ord Integer
-- Defined in ‘integer-gmp-1.0.0.1:GHC.Integer.Type’
instance Ord a => Ord (Maybe a) -- Defined in ‘GHC.Base’
...plus 22 others
...plus five instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In the second argument of ‘($)’, namely ‘quicksort []’
In the expression: print $ quicksort []
In an equation for ‘main’: main = print $ quicksort []
Where in the first message the print function demanded a Show instance - here you promised the quicksort to supply a list of orderables - but did not say which to use, so GHC complains about what Ord to use.
Both messages are due to the fact that [] is too polymorphic it could be a list of anything - [Int] is good, but it could also be something like [Int -> Bool] which is neither Showable nor Orderable.
You could as well supply quicksort with something weird like a
newtype HiddenInt = HI Int deriving (Ord) --but not Show
which would work for the quicksort function but not for print.
Side Note
Your quicksort functions need to be recursive in order to really be correct - as I pointed out in my comments - there is a logical problem in your algorithm - be sure to test your functions properly e.g.
import Data.List (sort)
main :: IO ()
main = do print $ "quicksort [10,9..1] == Just (sort [10,9..1]) is: "
++ show $ quicksort ([10,9..1]::Int]) == Just (sort ([10,9..1]::Int]))
print $ "quicksort [5,5,5] == Just (sort [5,5,5]) is: "
++ show $ quicksort ([5,5,5] :: [Int]) == Just (sort ([5,5,5] :: [Int]))
quicksort :: (Ord a) => [a] -> Maybe [a]
quicksort = ...
or if you are interested take a look at QuickCheck - which is a bit more advanced, but a step in the right direction for verifying your algorithms/functions work the way you expect them.

How and why is [1 .. 0] different from [1 .. -1] in Haskell?

I have defined the following function
let repl x n = [x | _ <- [1..n]]
which imitates the built-in replicate function.
While experimenting with it, I noticed a strange thing: repl 10 0 evaluates to [], while repl 10 -1 produces an error:
No instance for (Show (t10 -> [t0])) arising from a use of ‘print’
In a stmt of an interactive GHCi command: print it
On the other hand, both [1 .. 0] and [1 .. -1] evaluate to [] without producing any errors.
Moreover, both [42 | _ <- [1 .. 0]] and [42 | _ <- [1 .. -1]] evaluate to [] without errors.
So why does my function call result in an error where the explicit substitution doesn't? And more importantly, where does the apparent difference between [1 .. 0] and [1 .. -1] stem from?
And a final question: when I write:
repl 42 -1
the error is exactly the same as with repl 10 -1, i.e. it still has the (Show (t10 -> [t0])) bit in it. I was expecting it to have something like ((Show (t42 -> [t0]))). What's this 10?
Other answers have pointed out that you need to wrap -1 in parentheses. This is an odd corner of the Haskell 98 spec that jumps out to bite unexpectedly. It's not the case that you can never write a negative number without parentheses: -1 * 5 is fine. It's just that the unary prefix operator doesn't have higher precedence than the binary infix operator, so a - is frequently parsed as the latter. Whitespace around operators is not significant in Haskell.
And the incomprehensible typeclass error doesn't help. Incidentally, t10 and t0 are just placeholder type variables made up by the compiler; I don't think it has anything to do with the actual numeric literals you use. And informally, errors like Could not deduce (Num (a0 -> t)) usually indicate to me that a function is applied to too few arguments.
Alternatively, the (undocumented?) NegativeLiterals language extension in GHC 7.8 changes the meaning of -1 to address this problem.
> :set -XNegativeLiterals
> :t repl 10 -1
repl 10 -1 :: Num t => [t]
You have not included the full error message in your question, and if you had, you'd see that repl 10 -1 is parsed as (repl 10) - (1) which is not what you intended.
You'd get the same error with repl 10 +1.
You can often find clues as to how a program code is parsed, by looking closely into the error message. There's no harm in overusing parentheses, while you learn, either.
The program:
repl x n = [x | _ <- [1..n]] -- line 1
main = print (repl 10 -1) -- line 3
The message:
prog.hs:3:8:
No instance for (Show (t1 -> [t0])) arising from a use of `print'
Possible fix: add an instance declaration for (Show (t1 -> [t0]))
In the expression: print (repl 10 - 1)
In an equation for `main': main = print (repl 10 - 1)
prog.hs:3:15:
No instance for (Num t1) arising from a use of `repl'
The type variable `t1' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there are several potential instances:
instance Num Double -- Defined in `GHC.Float'
instance Num Float -- Defined in `GHC.Float'
instance Integral a => Num (GHC.Real.Ratio a)
-- Defined in `GHC.Real'
...plus three others
In the first argument of `(-)', namely `repl 10' --------- NB!
In the first argument of `print', namely `(repl 10 - 1)'
In the expression: print (repl 10 - 1)
prog.hs:3:20:
No instance for (Num t0) arising from the literal `10'
The type variable `t0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there are several potential instances:
instance Num Double -- Defined in `GHC.Float'
instance Num Float -- Defined in `GHC.Float'
instance Integral a => Num (GHC.Real.Ratio a)
-- Defined in `GHC.Real'
...plus three others
In the first argument of `repl', namely `10'
In the first argument of `(-)', namely `repl 10' --------- NB!
In the first argument of `print', namely `(repl 10 - 1)'
prog.hs:3:23:
No instance for (Num (t1 -> [t0])) arising from a use of `-'
Possible fix: add an instance declaration for (Num (t1 -> [t0]))
In the first argument of `print', namely `(repl 10 - 1)'
In the expression: print (repl 10 - 1)
In an equation for `main': main = print (repl 10 - 1)
Did you try [1..(-1)]? In Haskell, you cannot write negative numbers like -1 directly. You need to put them in parentheses. The reason is that Haskell doesn't have prefix unary operators because operators in Haskell are always infix. Hence -1 is parsed as [operator (-)] [numeric 1] and not [numeric -1].
This is what causes the problem. To avoid this problem, negative numbers must always be put in parentheses. This ensures that (-1) is parsed as [numeric -1]. It's one of the few corner cases which gives migraines to newcomers in Haskell.

Resources