Compiler aborts tests - function

I have tried to specify variables in functions, but it didn't help.
functions:
prop_unzip_check :: forall a b. Ord a => [(a,b)] -> Bool
prop_unzip_check xs = length (unzip (xs::[(a,b)])) >= 0
prop_merge_check :: forall a. Ord a => [a] -> [a] -> Bool
prop_merge_check xs ys = length (merge (xs::[a]) (ys::[a]))
== length (sort ((xs::[a]) ++ (ys::[a])))
And after compiling I receive this confusing error:
> Test property "prop_merge_check" ... aborted.
Reason: Ambiguous type variable `a0' arising from a use of `quickCheckBool'
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 QCGen -- Defined in `Test.QuickCheck.Arbitrary'
instance Arbitrary (a b c) => Arbitrary (WrappedArrow a b c)
-- Defined in `Test.QuickCheck.Arbitrary'
instance Arbitrary (m a) => Arbitrary (WrappedMonad m a)
-- Defined in `Test.QuickCheck.Arbitrary'
...plus 80 others
(use -fprint-potential-instances to see them all)
Ambiguous type variable `a0' arising from a use of `prop_merge_check'
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 (Encoding' a)
-- Defined in `Data.Aeson.Encoding.Internal'
instance Ord DotNetTime -- Defined in `Data.Aeson.Types.Internal'
instance Ord JSONPathElement
-- Defined in `Data.Aeson.Types.Internal'
...plus 310 others
(use -fprint-potential-instances to see them all)

The problem is solved by defining certain functions as Int instead of any type of functions 'a'.
> prop_unzip_check :: [(Int,Int)] -> Bool
> prop_unzip_check xs = length (unzip (xs::[(Int,Int)])) >= 0

Related

error message by list comprehension with floored float numbers and in lambda functions

I'm learning Haskell and have some problems with list comprehension.
If I define a function to get a list of the divisors of a given number, I get an error.
check n = [x | x <- [1..(floor (n/2))], mod n x == 0]
I don't get why it's causing an error. If I want to generate a list from 1 to n/2 I can do it with [1..(floor (n/2))], but not if I do it in the list comprehension.
I tried another way but I get also an error (in this code I want to get all so called "perfect numbers")
f n = [1..(floor (n/2))]
main = print $ filter (\t -> foldr (+) 0 (f t) == t) [2..100]
Usually it is better to start writing a signature. While signatures are often not required, it makes it easier to debug a single function.
The signature of your check function is:
check :: (RealFrac a, Integral a) => a -> [a]
The type of input (and output) a thus needs to be both a RealFrac and an Integral. While technically speaking we can make such type, it does not make much sense.
The reason this happens is because of the use of mod :: Integral a => a -> a -> a this requires x and n to be both of the same type, and a should be a member of the Integral typeclass.
Another problem is the use of n/2, since (/) :: Fractional a => a -> a -> a requires that n and 2 have the same type as n / 2, and n should also be of a type that is a member of Fractional. To make matters even worse, we use floor :: (RealFrac a, Integral b) => a -> b which enforces that n (and thus x as well) have a type that is a member of the RealFrac typeclass.
We can prevent the Fractional and RealFrac type constaints by making use of div :: Integral a => a -> a -> a instead. Since mod already required n to have a type that is a member of the Integral typeclass, this thus will not restrict the types further:
check n = [x | x <- [1 .. div n 2], mod n x == 0]
This for example prints:
Prelude> print (check 5)
[1]
Prelude> print (check 17)
[1]
Prelude> print (check 18)
[1,2,3,6,9]

Declare type of function in contract

so i am struggling a bit with type of functions.
I have a function
prop_merge_check xs ys = length (merge xs ys) == length (sort (xs ++ ys))
how can i assign type for each element of the function?
I tried this way
prop_merge_check :: Eq a => [a] -> [a] -> Bool
and also this way
prop_merge_check xs ys = length (merge (xs::[a]) (ys::[a])) == length (sort ((xs::[a]) ++ (ys::[a])))
But it doesn't seem to work out for me.
Need help pls
Errors are
• Ambiguous type variable ‘a0’ arising from a use of ‘merge’
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 a, Ord b) => Ord (Either a b)
-- Defined in ‘Data.Either’
instance Ord Ordering -- Defined in ‘GHC.Classes’
instance Ord Integer
-- Defined in ‘integer-gmp-1.0.2.0:GHC.Integer.Type’
...plus 23 others
...plus 98 instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In the first argument of ‘length’, namely
‘(merge (xs :: [a]) (ys :: [a]))’
In the first argument of ‘(==)’, namely
‘length (merge (xs :: [a]) (ys :: [a]))’
In the expression:
length (merge (xs :: [a]) (ys :: [a]))
== length (sort ((xs :: [a]) ++ (ys :: [a])))
And
• Ambiguous type variable ‘a0’ arising from a use of ‘merge’
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 a, Ord b) => Ord (Either a b)
-- Defined in ‘Data.Either’
instance Ord Ordering -- Defined in ‘GHC.Classes’
instance Ord Integer
-- Defined in ‘integer-gmp-1.0.2.0:GHC.Integer.Type’
...plus 23 others
...plus 98 instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In the first argument of ‘length’, namely
‘(merge (xs :: [a]) (ys :: [a]))’
In the first argument of ‘(==)’, namely
‘length (merge (xs :: [a]) (ys :: [a]))’
In the expression:
length (merge (xs :: [a]) (ys :: [a]))
== length (sort ((xs :: [a]) ++ (ys :: [a])))
As I suspected, the type is not part of the Eq type class, but is part of the Ord type class. Eq specifies how to equal two things and Ord specifies whether something is less than (LT), greater than (GT) or equal to (Eq) something.
Changing your type to: prop_merge_check :: Ord a => [a] -> [a] -> Bool should work.

Declare type of function in a function

I have two functions:
prop_merge_check :: Ord a => [a] -> [a] -> Bool
prop_merge_check xs ys = length (merge xs ys) == length (sort (xs ++ ys))
prop_unzip_check :: Ord a => [(a,b)] -> Bool
prop_unzip_check xs = length (unzip xs) >= 0
How can I declare the types of function in a function itself?
I tried this way, but it didn't work out for me.
prop_merge_check xs ys = length (merge (xs::[a]) (ys::[a]))
== length (sort ( (xs::[a]) ++ (ys::[a]) ))
prop_unzip_check xs = length (unzip (xs::[(a,b)])) >= 0
This is a side-effect of Haskell's implicit forall's. Haskell automatically adds 'forall's to all type signatures as necessary, these act as "scoping" rules which limit the names to a particular area. Haskell interprets your signature as:
prop_merge_check :: forall a. Ord a => [a] -> [a] -> Bool
prop_merge_check xs ys =
length (merge (xs::forall a. [a]) (ys:: forall a. [a])) == (length (sort ((xs:: forall a. [a]) ++ (ys:: forall a. [a]))))
That is; it sees every a in every signature as a completely different variable! That's why it can't make the types work properly. This is an annoying and unobvious quirk, but there's a way around it.
If we enable the ScopedTypeVariables and provide an explicit forall in the type signature we tell Haskell that we want the scope of the type variables to span the whole function body:
{-# LANGUAGE ScopedTypeVariables #-}
-- ^ Put that at the top of your module
prop_merge_check :: forall a. Ord a => [a] -> [a] -> Bool
prop_merge_check xs ys =
length (merge (xs::[a]) (ys::[a])) == (length (sort ((xs::[a]) ++ (ys::[a]))))
This version should compile, because now the a in all signatures is considered the same. We can quantify more than one type variable at a time:
prop_unzip_check :: forall a b. Ord a => [(a,b)] -> Bool
prop_unzip_check xs = length (unzip (xs::[(a,b)])) >= 0
Unfortunately there's not currently an easy way to do this sort of thing without adding the explicit forall in the top-level signature, but there are a few proposals for changes to this behaviour. They likely won't be coming any time soon though; so I wouldn't hold your breath.
Good luck! You can look up the docs on ScopedTypeVariables and ExistentialQuantification to learn more about this quirk.

Int and Num type of haskell

I have below code to take the args to set some offset time.
setOffsetTime :: (Ord a, Num b)=>[a] -> b
setOffsetTime [] = 200
setOffsetTime (x:xs) = read x::Int
But compiler says "Could not deduce (b ~ Int) from the context (Ord a, Num b) bound by the type signature for setOffsetTime :: (Ord a, Num b) => [a] -> b
Also I found I could not use 200.0 if I want float as the default value. The compilers says "Could not deduce (Fractional b) arising from the literal `200.0'"
Could any one show me some code as a function (not in the prelude) that takes an arg to store some variable so I can use in other function? I can do this in the main = do, but hope
to use an elegant function to achieve this.
Is there any global constant stuff in Hasekll? I googled it, but seems not.
I wanna use Haskell to replace some of my python script although it is not easy.
I think this type signature doesn't quite mean what you think it does:
setOffsetTime :: (Ord a, Num b)=>[a] -> b
What that says is "if you give me a value of type [a], for any type a you choose that is a member of the Ord type class, I will give you a value of type b, for any type b that you choose that is a member of the Num type class". The caller gets to pick the particular types a and b that are used each time setOffsetTime is called.
So trying to return a value of type Int (or Float, or any particular type) doesn't make sense. Int is indeed a member of the type class Num, but it's not any member of the type class Num. According to that type signature, I should be able to make a brand new instance of Num that you've never seen before, import setOffsetTime from your module, and call it to get a value of my new type.
To come up with an acceptable return value, you can only use functions that likewise return an arbitrary Num. You can't use any functions of particular concrete types.
Existential types are essentially a mechanism for allowing the callee to choose the value for a type variable (and then the caller has to be written to work regardless of what that type is), but that's not really something you want to be getting into while you're still learning.
If you are convinced that the implementation of your function is correct, i.e., that it should interpret the first element in its input list as the number to return and return 200 if there is no such argument, then you only need to make sure that the type signature matches that implementation (which it does not do, right now).
To do so, you could, for example, remove the type signature and ask ghci to infer the type:
$ ghci
GHCi, version 7.6.2: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude> :{
Prelude| let setOffsetTime [] = 200
Prelude| setOffsetTime (x : xs) = read x :: Int
Prelude| :}
Prelude> :t setOffsetTime
setOffsetTime :: [String] -> Int
Prelude> :q
Leaving GHCi.
$
And indeed,
setOffsetTime :: [String] -> Int
setOffsetTime [] = 200
setOffsetTime (x : xs) = read x :: Int
compiles fine.
If you want a slightly more general type, you can drop the ascription :: Int from the second case. The above method then tells you that you can write
setOffsetTime :: (Num a, Read a) => [String] -> a
setOffsetTime [] = 200
setOffsetTime (x : xs) = read x
From the comment that you added to your question, I understand that you want your function to return a floating-point number. In that case, you can write
setOffsetTime :: [String] -> Float
setOffsetTime [] = 200.0
setOffsetTime (x : xs) = read x
or, more general:
setOffsetTime :: (Fractional a, Read a) => [String] -> a
setOffsetTime [] = 200.0
setOffsetTime (x : xs) = read x

difference between (a -> a) and a -> a

I've noticed that (although I was once told that (a -> a) and a -> a meant the same thing), I get error messages when I use the (a -> a). Should I only use (a -> a) when using brackets amongst the types? (i.e. (5 + 3) instead of 5 + 3)? Just not quite certain of when it's necessary
(a -> a) and a -> a are the same alone,
ff :: (a -> a) -- this compiles
ff = id
gg :: a -> a
gg = id
h :: a -> a -> Bool
h _ _ = True
i = h ff gg -- this compiles => ff & gg are of the same type.
but will be different when combined with more types like:
a -> a -> b
(a -> a) -> b
This is because -> is right-associative, so a -> a -> b actually means a -> (a -> b) (take an a and return a function), which is different from (a -> a) -> b (take a function and return a b).
This is like (1+2)*3 is different from 1+2*3.
Parenthesization disambiguates several constructs in Haskell, when other information available to the compiler doesn't help:
Application associates to the left
so you can omit parens on function arguments.
Expressions involving infix operators are disambiguated by the operator's fixity.
so no need for parens in many cases with binary operators of different fixity.
Consecutive unparenthesized operators with the same precedence must both be either left or right associative to avoid a syntax error.
and finally:
Given an unparenthesized expression x op y op z, parentheses must be added around either x op y or y op z, unless certain conditions about precendence hold
My general advice, if the above statements don't make any sense: over-parenthesize things, until you learn the rules. Or, study the Haskell Report very hard.
Consider the expression 10 / 2 / 5. Is that the same as (10 / 2) / 5 or 10 / (2 / 5)? If you interpret / to be mathematical division, then the former is true, while the latter is false. So you see, the answer to your question is "there is a difference, but only sometimes".
Types are the opposite. a -> b -> c is the same as a -> (b -> c), and definitely not the same as (a -> b) -> c.
You say you're not quite sure when it's necessary: well here it is. When the argument to your function is also a function, then it is necessary.
Consider map :: (a -> b) -> [a] -> [b]. This is different than a -> b -> [a] -> [b], for you see, (a -> b) indicates a specific kind of function: a function from type a to type b.
iterate :: (a -> a) -> a -> [a] is more interesting. This function requires that the input and output types of the function in the first parameter must be the same.
You may be interested in reading up on currying and partial application. One good resource among many: Learn you a Haskell # Curried Functions
This only makes a difference when you're making higher order functions. For example:
f :: a -> a -> b
is a function that expects two arguments of type a and return a value of type b, like so
f 2 2
f True True
But the function
f :: (a -> a) -> b
Expects a function as an argument. The only time where a -> a and (a -> a) are the same if they're the only argument in type inference, like here
f :: (a -> a)
-- Same type as
f :: a -> a
The rules for () in typing are pretty much the same as in normal expressions. It's like expressions a level above.
They are the same. Could you describe the errors you get when you use (a -> a)? It works fine for me with ghci-7.0.3:
Prelude> let f :: (a -> a); f = id
Prelude> f "foo"
"foo"
Prelude>
In general, you need to use parentheses in types when you're using functions as arguments. For example, map :: (a -> b) -> [a] -> [b]. Without the parens, it would mean something else.