Haskell basic function definition problem - function

I'm learning Haskell and I'm trying to write a function to return a list of factors for a number. Here's what I have:
factors :: Int -> [Int]
factors n = [x | x <- [2..s], n `mod` x == 0]
where s = floor (sqrt n)
When I try to load the module in ghci, I get two errors,
p003.hs:3:14:
No instance for (RealFrac Int)
arising from a use of `floor' at p003.hs:3:14-27
Possible fix: add an instance declaration for (RealFrac Int)
In the expression: floor (sqrt n)
In the definition of `s': s = floor (sqrt n)
In the definition of `factors':
factors n = [x | x <- [2 .. s], n `mod` x == 0]
where
s = floor (sqrt n)
p003.hs:3:21:
No instance for (Floating Int)
arising from a use of `sqrt' at p003.hs:3:21-26
Possible fix: add an instance declaration for (Floating Int)
In the first argument of `floor', namely `(sqrt n)'
In the expression: floor (sqrt n)
In the definition of `s': s = floor (sqrt n)
Failed, modules loaded: none.
Any suggestions?

The parameter has type Int, so you cannot calculate a square root for it. You need to convert it to a floating point type first, which you can do with fromIntegral. Unlike some other languages, Haskell does not automatically promote integers to floating point numbers (nor do any other automatic type conversions).
So change sqrt n to sqrt (fromIntegral n).

The cause of the problem
The type of the sqrt function is
sqrt :: (Floating a) => a -> a
You can check this by typing :t sqrt in ghci.
Int is not an instance of Floating, which is why you're seeing the second error.
The cause of the first error is the same; checking :t floor reveals that the type is:
floor :: (RealFrac a, Integral b) => a -> b
The function is expecting an instance of RealFrac, and you're supplying an Int.
Typing :info RealFrac or :info Floating reveals that neither has an instance for Int, which is why the body of the error says
No instance for ... Int
The solution
The solution to this problem, is to make sure that the types are correct; they must be members of the proper type classes.
A simple way to do this is to use the fromIntegral function, which :t reveals is of type:
fromIntegral :: (Integral a, Num b) => a -> b
Using fromIntegral is necessary because the incoming type is Int, but the functions floor and sqrt operate on types RealFrac and Floating, respectively.
It's allowed because, as you can see from the type signature, fromIntegral returns an instance of Num, which includes both the RealFrac and Floating types. You can convince yourself of this by typing :info Num and :info Float into ghci, and viewing the output.
Making his change to your program would have the final result below, which should work as you want:
factors :: Int -> [Int]
factors n = [x | x <- [2..s], n `mod` x == 0]
where s = floor (sqrt $ fromIntegral n)
Further reading
Two good resources for understanding exactly what's going on are the Haskell tutorial's sections on Type Classes and Numbers.

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]

How to use predefined function (e.g. ==, tail) on my custom data type in Haskell?

I'm new to haskell and nothing I've read online really helped me with this. My assignment is to implement a typeclass VEC that has a function factor which either calculates the multiplication of two Integers or performs the dot product of two matrices if the user input wasn't two numbers but instead two lists of integers of type vector. My code looks as follows:
data Vector = VECTOR [Int] deriving (Show, Eq)
class VEC a where
factor :: a -> a -> a
instance VEC Int where
factor a b = a*b
instance VEC Vector where
factor xs [] = 0
factor xs ys = (head xs) * (head ys) + factor (tail xs) (tail ys)
I assumed the Vectors were of type [Int] but now I'm not so sure, since I get the following error message when trying to compile the code using Hugs:
Hugs> :l kdp
ERROR file:kdp.hs:7 - Type error in instance member binding
*** Term : []
*** Type : [a]
*** Does not match : Vector
So my questions would be: What does the first line actually mean? It was given along with the assignment and I've seen many similar definitions of data types but none with this particular pattern. And then how do I fix the problem of not being able to use predefined functions such as tail or in the above error case comparing a list of Integers with my custom data type? My guess is I have to define the operations on my own but I couldn't figure out how to do that.
When you write an instance for a class like
class C a where
method :: a -> a
you replace all of the parameter appearances (a) with the type you are writing instance for. For example in your case:
{-# LANGUAGE InstanceSigs #-}
instance VEC Vector where
factor :: Vector -> Vector -> Vector
factor _ _ = undefined
So you cannot match arguments of type Vector with pattern [] nor use head nor tail functions on it as they are working on lists. However, your Vector consists of lists, so you can simply unpack it:
instance VEC Vector where
factor _ (Vector []) = Vector [0] -- you need to return Vector as well
factor (Vector xs) (Vector ys) =
let Vector [x] = factor (Vector $ tail xs) (Vector $ tail ys)
in Vector [(head xs) * (head ys) + x]
This is very ugly and partial tho, you can use some builtin Data.List machinery to make it more sexy:
instance VEC Vector where
factor (Vector xs) (Vector ys) =
Vector [sum (zipWith (*) xs ys)]
As you are using deriving (Show, Eq), the == operator should just work.
You can generalize your type class to take two type variables to accommodate the two different operations of integer multiplication and vector dot products. This requires two GHC-specific extensions, though, precluding your use of Hugs.
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-}
-- a -> b means that the second type is uniquely determined by the
-- first. Without it, you would need explicitly type an expression
-- involving factor.
class VEC a b | a -> b where
factor :: a -> a -> b
instance VEC Int Int where
-- a ~ Int, b ~ Int
factor x y = x * y
-- newtype instead of data, for efficiency if nothing else
newtype Vector = VECTOR [Int] deriving (Show, Eq)
instance VEC Vector Int where
-- a ~ Vector, b ~ Int
factor (VECTOR xs) (VECTOR ys) = sum $ zipWith (*) xs ys
main = do
print $ factor (3 :: Int) 3
print $ factor (VECTOR [1,2,3]) (VECTOR [4,5,6])
Without the functional dependency, you would have to write
main = do
print (factor (3 :: Int) 3 :: Int)
print (factor (VECTOR [1,2,3]) (VECTOR [4,5,6]) :: Int)

Feeding data to Haskell twice function as explained by Erik Meijer lecture 7

Can somebody point me to how to feed data to:
twice f x = f (f x)
It's taken from Erik Meijer's lecture, and I have the feeling I can only truely understand when passing data to it. Now this only results in errors.
The derived type signature is (t -> t) -> t -> t. Pass any arguments that match and you won't get compiler errors. One example is twice (+1) 0.
The main mistake here is disregarding the type of twice. In Haskell types are very important, and explain precisely how you would call such a function.
twice :: (a -> a) -> a -> a
So, the function works in this way:
the caller chooses any type a they want
the caller passes a function f of type a -> a
the caller passes an argument of type a
twice finally produces a value of type a
Hence, we could do the following. We can choose, for instance, a = Int. Then define the function f as
myFun :: Int -> Int
myFun y = y*y + 42
then choose x :: Int as 10. Finally, we can make the call
twice myFun 10
Alternatively, we can use a lambda and skip the function definition above
twice (\y -> y*y + 42) 10
For illustration here are three functions called erik1, erik2, and erik3 with the same type signature.
erik1, erik2, erik3 ::(a -> a) -> a -> a
erik1 f x = f x
erik2 f x = f(f x) -- Equivalent to "twice"
erik3 f x = f(f(f x))
These eriks take two arguments, the first being a function and the second being a number. Let's choose sqrt as the function and the number to be 16 and run the three eriks. Here's what you get:
*Main> erik1 sqrt 16
4.0
*Main> erik2 sqrt 16
2.0
*Main> erik3 sqrt 16
1.4142135623730951
There are many things you can try, such as erik3 (/2) 16 = 2,because the f in the function allows you to use any appropriate function. In the particular case of sqrt, erik3 is equivalent to this statement in C:
printf ("Eighth root of 16 = %f \n", sqrt(sqrt(sqrt(16))));
Dr. Meijer Ch 7 1:48 to 3:37
As I watched this lecture last night a key point was made when Erik wrote the type signature as twice :: (a -> a) -> (a -> a) and said, "twice is a function that takes a to a and returns a new function from a to a, and by putting some extra parens it becomes painfully obvious that twice is a higher order function."
A C example that comes closer to illustrating that is:
#define eighthRoot(x) (sqrt(sqrt(sqrt(x))))
printf ("eigthtRoot(16) = %f \n", eighthRoot(16));

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 `(Integer a) => a -> Bool` and ` Integer -> Bool`?

I wrote my first program in Haskell today. It compiles and runs successfully. And since it is not a typical "Hello World" program, it in fact does much more than that, so please congrats me :D
Anyway, I've few doubts regarding my code, and the syntax in Haskell.
Problem:
My program reads an integer N from the standard input and then, for each integer i in the range [1,N], it prints whether i is a prime number or not. Currently it doesn't check for input error. :-)
Solution: (also doubts/questions)
To solve the problem, I wrote this function to test primality of an integer:
is_prime :: Integer -> Bool
is_prime n = helper n 2
where
helper :: Integer -> Integer -> Bool
helper n i
| n < 2 * i = True
| mod n i > 0 = helper n (i+1)
| otherwise = False
It works great. But my doubt is that the first line is a result of many hit-and-trials, as what I read in this tutorial didn't work, and gave this error (I suppose this is an error, though it doesn't say so):
prime.hs:9:13:
Type constructor `Integer' used as a class
In the type signature for `is_prime':
is_prime :: Integer a => a -> Bool
According to the tutorial (which is a nicely-written tutorial, by the way), the first line should be: (the tutorial says (Integral a) => a -> String, so I thought (Integer a) => a -> Bool should work as well.)
is_prime :: (Integer a) => a -> Bool
which doesn't work, and gives the above posted error (?).
And why does it not work? What is the difference between this line (which doesn't work) and the line (which works)?
Also, what is the idiomatic way to loop through 1 to N? I'm not completely satisfied with the loop in my code. Please suggest improvements. Here is my code:
--read_int function
read_int :: IO Integer
read_int = do
line <- getLine
readIO line
--is_prime function
is_prime :: Integer -> Bool
is_prime n = helper n 2
where
helper :: Integer -> Integer -> Bool
helper n i
| n < 2 * i = True
| mod n i > 0 = helper n (i+1)
| otherwise = False
main = do
n <- read_int
dump 1 n
where
dump i x = do
putStrLn ( show (i) ++ " is a prime? " ++ show (is_prime i) )
if i >= x
then putStrLn ("")
else do
dump (i+1) x
You are misreading the tutorial. It would say the type signature should be
is_prime :: (Integral a) => a -> Bool
-- NOT Integer a
These are different types:
Integer -> Bool
This is a function that takes a value of type Integer and gives back a value of type Bool.
Integral a => a -> Bool
This is a function that takes a value of type a and gives back a value of type Bool.
What is a? It can be any type of the caller's choice that implements the Integral type class, such as Integer or Int.
(And the difference between Int and Integer? The latter can represent an integer of any magnitude, the former wraps around eventually, similar to ints in C/Java/etc.)
The idiomatic way to loop depends on what your loop does: it will either be a map, a fold, or a filter.
Your loop in main is a map, and because you're doing i/o in your loop, you need to use mapM_.
let dump i = putStrLn ( show (i) ++ " is a prime? " ++ show (is_prime i) )
in mapM_ dump [1..n]
Meanwhile, your loop in is_prime is a fold (specifically all in this case):
is_prime :: Integer -> Bool
is_prime n = all nondivisor [2 .. n `div` 2]
where
nondivisor :: Integer -> Bool
nondivisor i = mod n i > 0
(And on a minor point of style, it's conventional in Haskell to use names like isPrime instead of names like is_prime.)
Part 1: If you look at the tutorial again, you'll notice that it actually gives type signatures in the following forms:
isPrime :: Integer -> Bool
-- or
isPrime :: Integral a => a -> Bool
isPrime :: (Integral a) => a -> Bool -- equivalent
Here, Integer is the name of a concrete type (has an actual representation) and Integral is the name of a class of types. The Integer type is a member of the Integral class.
The constraint Integral a means that whatever type a happens to be, a has to be a member of the Integral class.
Part 2: There are plenty of ways to write such a function. Your recursive definition looks fine (although you might want to use n < i * i instead of n < 2 * i, since it's faster).
If you're learning Haskell, you'll probably want to try writing it using higher-order functions or list comprehensions. Something like:
module Main (main) where
import Control.Monad (forM_)
isPrime :: Integer -> Bool
isPrime n = all (\i -> (n `rem` i) /= 0) $ takeWhile (\i -> i^2 <= n) [2..]
main :: IO ()
main = do n <- readLn
forM_ [1..n] $ \i ->
putStrLn (show (i) ++ " is a prime? " ++ show (isPrime i))
It is Integral a, not Integer a. See http://www.haskell.org/haskellwiki/Converting_numbers.
map and friends is how you loop in Haskell. This is how I would re-write the loop:
main :: IO ()
main = do
n <- read_int
mapM_ tell_prime [1..n]
where tell_prime i = putStrLn (show i ++ " is a prime? " ++ show (is_prime i))