How to get a pair (tuple) of integer and float? - haskell

I'm very much a beginner in Haskell, I'm trying to create a tuple of 2 elements, the first being an integer, and the second being a float. Example:
f1 n = [(x, x) | x <- [1 .. n]]
f2 n = [(x, 1 / x) | x <- [1 .. n]]
> f1 5
[(1,1),(2,2),(3,3),(4,4),(5,5)]
> f2 5
[(1.0,1.0),(2.0,0.5),(3.0,0.3333333333333333),(4.0,0.25),(5.0,0.2)]
f1 behaves as expected, returning a list of tuples of two integers.
f2 returns a list of tuples of two floats, but I was expecting it to return a list of tuples of one integer and one float.
How would I preserve the first tuple element type as integer, such that the output of f2 5 would look like: [(1,1.0),(2,0.5),(3,0.3333333333333333),(4,0.25),(5,0.2)]

The reason this happens is that the compiler sees 1/x, which requires not only the result to be floating (Fractional, actually) but also the argument x. This is because the numerical operators in Haskell have all-same-type signatures
(/) :: Fractional a => a -> a -> a
I.e. the compiler infers that x must already have floating type as well, and thus the left element of the tuple ends up as a float.
You can prevent this by dividing not by x itself but instead allowing for conversion:
Prelude> [(x, 1 / fromIntegral x) | x <- [1 .. 9]]
[(1,1.0),(2,0.5),(3,0.3333333333333333),(4,0.25),(5,0.2),(6,0.16666666666666666),(7,0.14285714285714285),(8,0.125),(9,0.1111111111111111)]
Additionally, one thing you should always try when the types don't seem right is to add an explicit signature. This way you can also enforce the computation to be carried out in other, perhaps more suitable types such as Rational:
Prelude> [(x, 1 / fromIntegral x) | x <- [1 .. 9]] :: [(Int, Rational)]
[(1,1 % 1),(2,1 % 2),(3,1 % 3),(4,1 % 4),(5,1 % 5),(6,1 % 6),(7,1 % 7),(8,1 % 8),(9,1 % 9)]
Also, you'll then get a clear-cut compiler error if you try something that doesn't work, instead of silently unexpected results.

Related

sum of elements multiplied by 3 in haskell

I want to create a function which takes an n elements long list and returns sum of all elements multiplied by 3. The way I do it is here:
times3::Int->Integer
times3 x = sum [map (3*) [1..x]]
This code however results in the following error:
Couldn't match expected type `Integer' with actual type `[Int]'
Do you have any idea why is this happening?
[map (3*) [1..x]] is a list of length one, since [ some expression here ] is always a singleton list. In your code it's the list-of-lists [[3,6,...,3*x]] of type [[Int]] as the compiler reported.
Your type signature claims the result is Integer, and to obtain that, we would need to start with list of type [Integer]. The compiler checks the type equality [[Int]] ~ [Integer] and complains that [Int] is not Integer, hence the type error.
Instead, (map (3*) [1..x]) is a list of length x, namely [3,6,...,3*x], which is of type [Int]. This is the list I think you intended to use.
Since this list is not a [Integer], you either have to perform a conversion using fromIntegral or, more simply, to change your type signature in the function.
Another alternative would be to make the argument x an Integer.
#chi's answer explains what the problem is with the current implementation. The only thing I want to add is that the sum of *3, 6, 9, …, 3×n; can be determined without enumerating over a list. Indeed the sum:
n n
--- ---
\ \
/ 3 i = 3 / i
--- ---
i=1 i=1
the sum if 1, 2, …, n can be calculated with n×(n+1)/2, so we can calculate the sum with:
times3 :: Int -> Integer
times3 n = 3 * div (n * (ni+1)) 2
where ni = fromIntegral n
or without converting an Int to Integer and for any Integral type:
times3 :: Integral i => i -> i
times3 n = 3 * div (n * (n+1)) 2

How to display function output as a list, [a], instead of a string, show [a], in context of the example code below

I am starting to learn some programming and I have been given the following exercise:
"Create a function named divisors that takes an integer n > 1 and returns an array with all of the integer's divisors(except for 1 and the number itself), from smallest to largest. If the number is prime return the string '(integer) is prime'.
Hint: Use divisors :: (Show a, Integral a) => a -> Either String [a]"
I do not yet understand how to employ the Either type, so in the interim I have decided to begin tackling the problem in baby steps.
Since part of the exercise requires constructing a function to distinguish between prime numbers and non-prime numbers, I decided to first create a provisional function: if the number (a) is not prime, I must display the list of its divisors [1..a]. If the number (a) is prime, I must display the string "(a) is prime".
The following code works:
divisors a = if length [i | i <- [1..a], mod a i == 0 ] > 2
then show [i | i <- [1..a], mod a i == 0 ]
else show a ++ " is prime"
Some output of this function is:
[1 of 1] Compiling Main ( program.hs, interpreted )
Ok, one module loaded.
*Main> divisors 1
"1 is prime"
*Main> divisors 2
"2 is prime"
*Main> divisors 3
"3 is prime"
*Main> divisors 4
"[1,2,4]"
*Main> divisors 5
"5 is prime"
*Main> divisors 6
"[1,2,3,6]"
*Main> divisors 7
"7 is prime"
However, I do need to display the list as a list [1..a] and not a string "[1..a]". I thus erased (show) from the (then) statement:
divisors a = if length [i | i <- [1..a], mod a i == 0 ] > 2
then [i | i <- [1..a], mod a i == 0 ]
else show a ++ " is prime"
but this throws up an error:
program.hs:11:42: error:
* No instance for (Integral Char) arising from a use of `mod'
* In the first argument of `(==)', namely `mod a i'
In the expression: mod a i == 0
In a stmt of a list comprehension: mod a i == 0
|
11 | divisors a = if length [i | i <- [1..a], mod a i == 0 ] > 2
| ^^^^^^^
Failed, no modules loaded.
I do not understand exactly what went wrong and need someone to explain how to display the output of non-prime numbers as a list instead of a string representation of the list.
I do not mind if someone wants to explain how to answer the original exercise question employing the Either type in the solution, if they are willing to explain how to re-formulate my function to employ the Either type properly.
EDIT:
After reading some responses, I attempted the following:
divisors :: (Show a, Integral a) => a -> Either String [a]
divisors a = if length [i | i <- [2..a], mod a i == 0] > 1
then Right [i | i <- [2..a-1], mod a i == 0]
else Left (show a ++ " is prime")
and it seems to be working!
Thank you for the suggestions.
From #RobinZigmond: Well you've discovered why you need Either. Haskell has a strong static type system, and a function needs to return values of a specific type. It's not possible for a function to do as you want and return a string on some inputs and a list of integers on other inputs (as it would be in a dynamic language). But that is what Either is for. A value of type Either a b is either Left x where x is a value of type a, or Right y where y is a value of type b. Hopefully you can now see why this would be useful for your case.
From #chi: the construct
if condition then x else y
requires x and y to be of the same type. If they are not, say:
x :: TypeX
y :: TypeY
you can convert both to Either TypeX TypeY as follows:
if condition then Left x else Right y
Since now the two if branches have the same type Either TypeX TypeY, it type checks, and that type will be the type of the value resulting from the if.
From the original poster, #nutbunny: After reading some responses, I attempted the following:
divisors :: (Show a, Integral a) => a -> Either String [a]
divisors a = if length [i | i <- [2..a], mod a i == 0] > 1
then Right [i | i <- [2..a-1], mod a i == 0]
else Left (show a ++ " is prime")
and it seems to be working!
Thank you for the suggestions!

Unresolved top level overloading

Task is to find all two-valued numbers representable as the sum of the sqrt's of two natural numbers.
I try this:
func = [sqrt (x) + sqrt (y) | x <- [10..99], y <- [10..99], sqrt (x) `mod` 1 == 0, sqrt (y) `mod` 1 == 0]
Result:
Unresolved top-level overloading Binding : func
Outstanding context : (Integral b, Floating b)
How can I fix this?
This happens because of a conflict between these two types:
sqrt :: Floating a => a -> a
mod :: Integral a => a -> a -> a
Because you write mod (sqrt x) 1, and sqrt is constrained to return the same type as it takes, the compiler is left trying to find a type for x that simultaneously satisfies the Floating constraint of sqrt and the Integral constraint of mod. There are no types in the base library that satisfy both constraints.
A quick fix is to use mod' :: Real a => a -> a -> a:
import Data.Fixed
func = [sqrt (x) + sqrt (y) | x <- [10..99], y <- [10..99], sqrt (x) `mod'` 1 == 0, sqrt (y) `mod'` 1 == 0]
However, from the error you posted, it looks like you may not be using GHC, and mod' is probably a GHC-ism. In that case you could copy the definition (and the definition of the helper function div') from here.
But I recommend a more involved fix. The key observation is that if x = sqrt y, then x*x = y, so we can avoid calling sqrt at all. Instead of iterating over numbers and checking if they have a clean sqrt, we can iterate over square roots; their squares will definitely have clean square roots. A straightforward application of this refactoring might look like this:
sqrts = takeWhile (\n -> n*n <= 99)
. dropWhile (\n -> n*n < 10)
$ [0..]
func = [x + y | x <- sqrts, y <- sqrts]
Of course, func is a terrible name (it's not even a function!), and sqrts is a constant we could compute ourselves, and is so short we should probably just inline it. So we might then simplify to:
numberSums = [x + y | x <- [4..9], y <- [4..9]]
At this point, I would be wondering whether I really wanted to write this at all, preferring just
numberSums = [8..18]
which, unlike the previous iteration, doesn't have any duplicates. It has lost all of the explanatory power of why this is an interesting constant, though, so you would definitely want a comment.
-- sums of pairs of numbers, each of whose squares lies in the range [10..99]
numberSums = [8..18]
This would be my final version.
Also, although the above definitions were not parameterized by the range to search for perfect squares in, all the proposed refactorings can be applied when that is a parameter; I leave this as a good exercise for the reader to check that they have understood each change.

Generating Cartesian products in Haskell

I am trying to generate all possible combinations of n numbers. For example if n = 3 I would want the following combinations:
(0,0,0), (0,0,1), (0,0,2)... (0,0,9), (0,1,0)... (9,9,9).
This post describes how to do so for n = 3:
[(a,b,c) | m <- [0..9], a <- [0..m], b <- [0..m], c <- [0..m] ]
Or to avoid duplicates (i.e. multiple copies of the same n-uple):
let l = 9; in [(a,b,c) | m <- [0..3*l],
a <- [0..l], b <- [0..l], c <- [0..l],
a + b + c == m ]
However following the same pattern would become very silly very quickly for n > 3. Say I wanted to find all of the combinations: (a, b, c, d, e, f, g, h, i, j), etc.
Can anyone point me in the right direction here? Ideally I'd rather not use a built in funtion as I am trying to learn Haskell and I would rather take the time to understand a peice of code than just use a package written by someone else. A tuple is not required, a list would also work.
My other answer gave an arithmetic algorithm to enumerate all the combinations of digits. Here's an alternative solution which arises by generalising your example. It works for non-numbers, too, because it only uses the structure of lists.
First off, let's remind ourselves of how you might use a list comprehension for three-digit combinations.
threeDigitCombinations = [[x, y, z] | x <- [0..9], y <- [0..9], z <- [0..9]]
What's going on here? The list comprehension corresponds to nested loops. z counts from 0 to 9, then y goes up to 1 and z starts counting from 0 again. x ticks the slowest. As you note, the shape of the list comprehension changes (albeit in a uniform way) when you want a different number of digits. We're going to exploit that uniformity.
twoDigitCombinations = [[x, y] | x <- [0..9], y <- [0..9]]
We want to abstract over the number of variables in the list comprehension (equivalently, the nested-ness of the loop). Let's start playing around with it. First, I'm going to rewrite these list comprehensions as their equivalent monad comprehensions.
threeDigitCombinations = do
x <- [0..9]
y <- [0..9]
z <- [0..9]
return [x, y, z]
twoDigitCombinations = do
x <- [0..9]
y <- [0..9]
return [x, y]
Interesting. It looks like threeDigitCombinations is roughly the same monadic action as twoDigitCombinations, but with an extra statement. Rewriting again...
zeroDigitCombinations = [[]] -- equivalently, `return []`
oneDigitCombinations = do
z <- [0..9]
empty <- zeroDigitCombinations
return (z : empty)
twoDigitCombinations = do
y <- [0..9]
z <- oneDigitCombinations
return (y : z)
threeDigitCombinations = do
x <- [0..9]
yz <- twoDigitCombinations
return (x : yz)
It should be clear now what we need to parameterise:
combinationsOfDigits 0 = return []
combinationsOfDigits n = do
x <- [0..9]
xs <- combinationsOfDigits (n - 1)
return (x : xs)
ghci> combinationsOfDigits' 2
[[0,0],[0,1],[0,2],[0,3],[0,4],[0,5],[0,6],[0,7],[0,8],[0,9],[1,0],[1,1] ... [9,8],[9,9]]
It works, but we're not done yet. I want to show you that this is an instance of a more general monadic pattern. First I'm going to change the implementation of combinationsOfDigits so that it folds up a list of constants.
combinationsOfDigits n = foldUpList $ replicate n [0..9]
where foldUpList [] = return []
foldUpList (xs : xss) = do
x <- xs
ys <- foldUpList xss
return (x : ys)
Looking at the definiton of foldUpList :: [[a]] -> [[a]], we can see that it doesn't actually require the use of lists per se: it only uses the monad-y parts of lists. It could work on any monad, and indeed it does! It's in the standard library, and it's called sequence :: Monad m => [m a] -> m [a]. If you're confused by that, replace m with [] and you should see that those types mean the same thing.
combinationsOfDigits n = sequence $ replicate n [0..9]
Finally, noting that sequence . replicate n is the definition of replicateM, we get it down to a very snappy one-liner.
combinationsOfDigits n = replicateM n [0..9]
To summarise, replicateM n gives the n-ary combinations of an input list. This works for any list, not just a list of numbers. Indeed, it works for any monad - though the "combinations" interpretation only makes sense when your monad represents choice.
This code is very terse indeed! So much so that I think it's not entirely obvious how it works, unlike the arithmetic version I showed you in my other answer. The list monad has always been one of the monads I find less intuitive, at least when you're using higher-order monad combinators and not do-notation.
On the other hand, it runs quite a lot faster than the number-crunching version. On my (high-spec) MacBook Pro, compiled with -O2, this version calculates the 5-digit combinations about 4 times faster than the version which crunches numbers. (If anyone can explain the reason for this I'm listening!)
What are all the combinations of three digits? Let's write a few out manually.
000, 001, 002 ... 009, 010, 011 ... 099, 100, 101 ... 998, 999
We ended up simply counting! We enumerated all the numbers between 0 and 999. For an arbitrary number of digits this generalises straightforwardly: the upper limit is 10^n (exclusive), where n is the number of digits.
Numbers are designed this way on purpose. It would be jolly strange if there was a possible combination of three digits which wasn't a valid number, or if there was a number below 1000 which couldn't be expressed by combining three digits!
This suggests a simple plan to me, which just involves arithmetic and doesn't require a deep understanding of Haskell*:
Generate a list of numbers between 0 and 10^n
Turn each number into a list of digits.
Step 2 is the fun part. To extract the digits (in base 10) of a three-digit number, you do this:
Take the quotient and remainder of your number with respect to 100. The quotient is the first digit of the number.
Take the remainder from step 1 and take its quotient and remainder with respect to 10. The quotient is the second digit.
The remainder from step 2 was the third digit. This is the same as taking the quotient with respect to 1.
For an n-digit number, we take the quotient n times, starting with 10^(n-1) and ending with 1. Each time, we use the remainder from the last step as the input to the next step. This suggests that our function to turn a number into a list of digits should be implemented as a fold: we'll thread the remainder through the operation and build a list as we go. (I'll leave it to you to figure out how this algorithm changes if you're not in base 10!)
Now let's implement that idea. We want calculate a specified number of digits, zero-padding when necessary, of a given number. What should the type of digits be?
digits :: Int -> Int -> [Int]
Hmm, it takes in a number of digits and an integer, and produces a list of integers representing the digits of the input integer. The list will contain single-digit integers, each one of which will be one digit of the input number.
digits numberOfDigits theNumber = reverse $ fst $ foldr step ([], theNumber) powersOfTen
where step exponent (digits, remainder) =
let (digit, newRemainder) = remainder `divMod` exponent
in (digit : digits, newRemainder)
powersOfTen = [10^n | n <- [0..(numberOfDigits-1)]]
What's striking to me is that this code looks quite similar to my English description of the arithmetic we wanted to perform. We generate a powers-of-ten table by exponentiating numbers from 0 upwards. Then we fold that table back up; at each step we put the quotient on the list of digits and send the remainder to the next step. We have to reverse the output list at the end because of the right-to-left way it got built.
By the way, the pattern of generating a list, transforming it, and then folding it back up is an idiomatic thing to do in Haskell. It's even got its own high-falutin' mathsy name, hylomorphism. GHC knows about this pattern too and can compile it into a tight loop, optimising away the very existence of the list you're working with.
Let's test it!
ghci> digits 3 123
[1, 2, 3]
ghci> digits 5 10101
[1, 0, 1, 0, 1]
ghci> digits 6 99
[0, 0, 0, 0, 9, 9]
It works like a charm! (Well, it misbehaves when numberOfDigits is too small for theNumber, but never mind about that.) Now we just have to generate a counting list of numbers on which to use digits.
combinationsOfDigits :: Int -> [[Int]]
combinationsOfDigits numberOfDigits = map (digits numberOfDigits) [0..(10^numberOfDigits)-1]
... and we've finished!
ghci> combinationsOfDigits 2
[[0,0],[0,1],[0,2],[0,3],[0,4],[0,5],[0,6],[0,7],[0,8],[0,9],[1,0],[1,1] ... [9,7],[9,8],[9,9]]
* For a version which does require a deep understanding of Haskell, see my other answer.
combos 1 list = map (\x -> [x]) list
combos n list = foldl (++) [] $ map (\x -> map (\y -> x:y) nxt) list
where nxt = combos (n-1) list
In your case
combos 3 [0..9]

Problems obtaining the list of divisors of a number in Haskell

This is not a duplicate question. Read below...
I'm declaring the following function:
divisors x = [(a, x/a) | a <- [2..(sqrt x)], x `mod` a == 0]
What I want to obtain is the divisors of x: A list of tuples that will contain (n, k) such as n * k = x
Example:
> divisors x
[(1,10), (2, 5)]
Why the above code isn't working?
It gives me the error:
*Main> divisors 10
<interactive>:1:0:
Ambiguous type variable `t' in the constraints:
`Floating t'
arising from a use of `divisors' at <interactive>:1:0-10
`Integral t'
arising from a use of `divisors' at <interactive>:1:0-10
Probable fix: add a type signature that fixes these type variable(s)
I've tried manually setting the signature of the function without success...
The problem is sqrt returns a Floating a, and you really just want integers when finding divisors. You can turn a Floating a into an Integral a with ceiling, floor or round. I will use ceiling, as I'm not sure if using floor or average won't skip a divisor.
The sqrt function also only accepts a floating number, so you will have to convert an integer into a floating before giving it to it (this can be done with fromIntegral).
Also, you use /, which also works with floating numbers. Using div is better as it works with integral numbers (rounding when necessary).
divisors x = [(a, x `div` a) | a <- [2..(ceiling $ sqrt $ fromIntegral x)], x `mod` a == 0]
With this, divisors 10 will give [(2,5)] (your code stops the (1,10) case from happening - I'm guessing this was intentional). Unfortunately you will get duplicates, eg divisors 12 will return [(2,6),(3,4),(4,3)], but that shouldn't be too hard to fix if it is a problem.
You can see the problem if you ask for the type:
divisors :: (Integral t, Floating t) => t -> [(t, t)]
and then check what things are both Integral and Floating:
Prelude> :info Floating
class Fractional a => Floating a where
instance Floating Float -- Defined in GHC.Float
instance Floating Double -- Defined in GHC.Float
and
Prelude> :info Integral
class (Real a, Enum a) => Integral a where
instance Integral Integer -- Defined in GHC.Real
instance Integral Int -- Defined in GHC.Real
so, it can be neither Int, Integer, Float or Double. You're in trouble...
Thankfully, we can convert between types, so that while sqrt needs a Floating, and mod needs an Integral (btw, rem is faster), we can either, e.g., do away with floating point division:
divisors :: Integer -> [(Integer, Integer)]
divisors x = [(a, x `div` a) | a <- [2..ceiling (sqrt (fromIntegral x))], x `rem` a == 0]
> divisors 100
[(2,0),(4,0),(5,0),(10,0)]
However, you need to think hard about what you really mean to do when converting integer types to floating point, via sqrt...
In Haskell, integer division and fractional division are different operations, and have different names. The slash operator, /, is for fractional division. Integer division is accomplished with div or quot (the difference between the two having to do with the behavior when there are negative numbers involved).
Try replacing x/a with
x `quot` a
instead.
The compiler error tells you exactly this: that you're treating a type sometimes as an integral number (by using mod), and sometimes as a fractional number (by using /), and it's not sure how to pick a type that acts like both of those.
You'll have a similar issue with sqrt, once that's sorted, though. There again, you need to be consistent about whether your types are integers or (in that case) floating point. For the purpose of finding possible divisors, it should suffice to range up to the greatest integer less that the floating point, so consider using floor (sqrt (fromIntegral x))). The fromIntegral converts x (which must have an integral type) to a different type -- in this case, it will default to Double. The floor then converts the Double result back into an integral type.
Instead of taking the square-root to bound the search, you can allow the comprehension to range over an infinite list, and use takeWhile to stop the search when the remainder is greater than the divisor:
divisors x = takeWhile (uncurry (<=)) [(a, x `div` a) | a <- [1..], x `mod` a == 0]
> divisors 100
[(1,100),(2,50),(4,25),(5,20),(10,10)]
Note: your original example shows (1,10) as one of the divisors of 10, so I started the comprehension from 1 instead of 2.
Hmm, this does search beyond the square-root until it hits the next factor above.
How about this:
divisors x = [(a, x `div` a) | a <- takeWhile ((<= x) . (^2)) [1..], x `mod` a == 0]

Resources