create a function to sum the odd square in haskell - haskell

sumoddsquare' :: (Num a) => [a] -> a
sumoddsquare' = sum [x^2 | x <- [1..5], odd x]
My desired output is 35
The syntax error I get is
Couldn't match expected type `[a] -> a'
with actual type `[Integer]'
In the expression: [x ^ 2 | x <- [1 .. 9999], odd x]
In an equation for sumoddsquare':
sumoddsquare' = [x ^ 2 | x <- [1 .. 9999], odd x]
Can you explain this syntax error and also provide a solution for this question?

You've given sumoddsquare' the type Num a => [a] -> a, but you've left off any parameter. Maybe you meant
sumoddsquare' xs = sum [x^2 | x <- xs, odd x]
Although the Num constraint is not sufficient here, inspect the types of ^2 and odd to determine what you should be using. (spoilers below)
Judging by the error message, you've actually defined sumoddsquare' in your code as
sumoddsquare' :: [a] -> a
sumoddsquare' = [x^2 | x <- [1..9999], odd x]
Rather than what you've posted above. Now, you've given the type [a] -> a to sumoddsquares' explicitly, the compiler takes that as a fact, but then it sees the definition. You don't define the argument explicitly in the definition, so the compiler thinks you're defining the function in point-free style. When it sees the right hand side of the =, it gets confused because [x^2 | x <- [1..9999], odd x] has the type [Integer], but it has already accepted the fact that sumoddsquares' has the type [a] -> a. It doesn't know how to reconcile this, so it throws the error you see.
You can usually find the source of these types of error messages by commenting out the explicit type signature. If it then compiles, you can inspect the type in GHCi by doing
> :load sumoddsquare_no_type_sig.hs
> :type sumoddsquare'
[Integer]
And this would tell you that sumoddsquare' is not a function. However, you want it to be a function, so how do you fix this? First, look at the definition. Are all of your arguments declared explicitly? If no, add them.
-- sumoddsquare' :: Num a => [a] -> a
sumoddsquare' xs = [x^2 | x <- [1..9999], odd x]
Then you see
> :reload
> :type sumoddsquare'
[a] -> [Integer]
That's at least a function, but how do we get from the very general type [a] to [Integer]? Since we currently know nothing about a, then this function must not depend on the first argument at all! We can then look through our definition to find where a list might go
-- sumoddsquare' :: Num a => [a] -> a
sumoddsquare' xs = [x^2 | x <- xs, odd x]
-- ^--- This is the only place I saw a list used
Then
> :reload
> :type sumoddsquare'
Integral a => [a] -> [a]
That's closer! We see that the input has been restricted to Integral and we return a more general type than just [Integer]. This tells us we first need to fix the constraint in our type signature from Num a to Integral a. The last puzzle is figuring out how to convert Integral a => [a] into Integral a => a. We want to sum, so now we see that we've left out the sum function in front of the list comprehension
-- sumoddsquare' :: Integral a => [a] -> a
sumoddsquare' xs = sum [x^2 | x <- xs, odd x]
And finally
> :reload
> :type sumoddsquare'
Integral a => [a] -> a
We have a type that matches what we want. We can now uncomment the type signature in our source code.
As a bonus, this problem can be solved entirely with higher order functions as
sumoddsquares' xs = sum $ map (^2) $ filter odd $ xs
-- or point free as
-- sumoddsquares' = sum . map (^2) . filter odd
And in fact, all list comprehensions are just syntactic sugar for maps, filters, and concats. These two pieces of code end up being essentially identical after compilation.

Related

How to check that all list items are odd and bigger than 10?

I need to check if a list only contains odd numbers, bigger than 10.
This is what I did.
f :: [Int] -> Bool
f xs= [x |x<-xs, x >10, odd x]
Why does this not work?
When you write [x |x<-xs, x >10, odd x] you're making up a list of Ints, a [Int], not a Boolean. For instance you can verify that
[x | x <- [1..20], x > 10, odd x] is the list [11,13,15,17,19]. So it does contain the numbers that you want, but how do you tell that those are all of the numebrers in xs?
You could certainly equate that list to xs itself, and that would work:
f xs = xs == [x |x<-xs, x >10, odd x]
This way the == ensures that when you only take odd numbers greater than 10 from xs you get back exactly xs, meaning that all numbers satisfy the predicate.
Maybe this is the mistake you were looking for.
I'm not sure whether this solution traverses xs twice (once to extract the entries satisfying the predicate, and once to check for equality) or not. It looks very simple, so I can't help but think that the list is traversed only once.
Anyway, another strategy is to stick to your request: you want all numbers x from the list xs for which odd x and x > 10 are both True:
f :: [Int] -> Bool
f xs = all (\x -> odd x && x > 10) xs
By noticing that both sides have a trailing xs, you can reduce the definition:
f :: [Int] -> Bool
f = all (\x -> odd x && x > 10)
And that lambda, if you want, could be define more succintly as (odd & (> 10)), thus getting
f :: [Int] -> Bool
f = all (odd & (> 10))
provided you import Control.Monad (liftM2) and define
(&) :: (a -> Bool) -> (a -> Bool) -> (a -> Bool)
(&) = liftM2 (&&)
Your type signature mentions that the function returns a boolean value, but your proposed body returns a list of numbers. Haskell has no automatic conversions such as Lisp.
Should you wish to stick to pedestrian code, you could get the sublist of offending numbers, and just check that the sublist is empty.
f :: [Int] -> Bool
f xs = let offenders = [x | x <- xs, x <= 10 || even x]
in (null offenders)
Note that due to the laziness of the language runtime, evaluation of offenders stops as soon as we find a first element.
Should you want something a bit more haskell-ish, you can use the sequence :: (Traversable t, Monad m) => t (m a) -> m (t a) polymorphic library function to turn a list of predicates into a single function returning a list of boolean values, then pass that list to and. That checks one number.
Then use all to apply these checks to all numbers in the input list. Like this:
f2 :: [Int] -> Bool
f2 = all (and . sequence [(>10), odd])
Explanation:
To understand how exactly the sequence function gets specialized by the compiler, one can use the TypeApplications language extension.
With the extension enabled, given 3 type arguments, expression sequence #tt #tm #ta maps tt to the Traversable instance, tm to the Monad instance and ta to argument type a.
$ ghci
GHCi, version 8.8.4: https://www.haskell.org/ghc/ :? for help
λ>
λ> :type sequence
sequence :: (Traversable t, Monad m) => t (m a) -> m (t a)
λ>
λ> :set -XTypeApplications
λ>
We start with the easiest part, mapping tt to lists and ta to Bool, leaving tm undefined as an underscore _:
λ>
λ> :type sequence #[] #_ #Bool
sequence #[] #_ #Bool :: Monad _ => [_ Bool] -> _ [Bool]
λ>
Now, if we assign tm to “function of an Int variable”, we have the whole picture:
λ>
λ> :type sequence #[] #((->)Int) #Bool
sequence #[] #((->)Int) #Bool :: [Int -> Bool] -> Int -> [Bool]
λ>
The last type can be interpreted as [Int -> Bool] -> (Int -> [Bool]), that is, function sequence transforming a list of predicates into a single function returning a list of boolean values.

why is test for non-equality not working in this list comprehension?

In GHCi entering the following two lines returns a list of lists of two numbers from an input list of numbers such that all combinations are listed, but not using the same element twice.
Prelude> a = [1,3,7,10,25,50]
Prelude> [(x,y) | x <- a, y <- a, x /= y ]
[(1,3),(1,7),(1,10),(1,25),(1,50),(3,1),(3,7),(3,10),(3,25),(3,50),(7,1),(7,3),(7,10),(7,25),(7,50),(10,1),(10,3),(10,7),(10,25),(10,50),(25,1),(25,3),(25,7),(25,10),(25,50),(50,1),(50,3),(50,7),(50,10),(50,25)]
When I write similar code in my .hs program, the compiler keeps rejecting any guard which tests for Equality or Inequality. i.e.
choices :: [a] -> [[a]]
choices [] = [[]]
choices [x] = [[x]]
choices xs = [[m,n] | m <- xs, n <- xs, m /= n ]
The compiler highlights the m /= n. Removing that guard (m =/ n) then the list comprehension works (with duplicate uses of elements of list a) Is this something to do with the compiler not knowing the type of m and n such that it can't assure they are in the type class Ord?
Not all types are members of the Eq typeclass. For example you can not check if two IO Ints are equal.
You should specify a type constraint that specifies that this will work for all types that are a member of the Eq typeclass your implementation:
choices :: Eq a => [a] -> [[a]]
choices [] = [[]]
choices [x] = [[x]]
choices xs = [[m,n] | m <- xs, n <- xs, m /= n ]
For the given sample input, we obtain:
Prelude> choices [1,3,7,10,25,50]
[[1,3],[1,7],[1,10],[1,25],[1,50],[3,1],[3,7],[3,10],[3,25],[3,50],[7,1],[7,3],[7,10],[7,25],[7,50],[10,1],[10,3],[10,7],[10,25],[10,50],[25,1],[25,3],[25,7],[25,10],[25,50],[50,1],[50,3],[50,7],[50,10],[50,25]]
In case of doubt, you can always run the thing under the ghci interpreter:
$ ghci
λ>
λ> choices xs = [[m,n] | m <- xs, n <- xs, m /= n ]
λ>
λ> choices [1,2]
[[1,2],[2,1]]
λ>
So far so good. But what type did ghci infer for the choices function ?
λ>
λ> :type choices
choices :: Eq a => [a] -> [[a]]
λ>
λ>
Voilà ! you have your missing type constraint.
GHC will not assume that type α offers some Ord or Eq interface, unless told so explicitely.

Sort a list of Int pairs by the difference of the values (a, b)

How do I sort a list of Int pairs by the difference of the values |first - second| in an ascending order?
For calculating the difference I wrote this piece of code:
ab :: (Int, Int) -> Int
ab (x, y) = if x - y >= 0 then (x - y)
else (x - y) * (-1)
I wanted to use quicksort on the values I get:
sort :: [(Int,Int)] -> [(Int,Int)]
sort [] = []
sort (x:xs) = sort smallerOrEqual ++ [x] ++ sort larger
where smallerOrEqual = [a | a <- xs, a <= x]
larger = [a | a <- xs, a > x]
The problem is how do I build my ab function into the sort function? I have tried several ways but always got compiler errors.
Let's do that with the standard library functions only!
First of all, there is a generic version of sorting function named sortBy (I'll show the types of relevant functions as we go, using GHCi's brilliant :t command):
ghci> import Data.List
ghci> :t sortBy
sortBy :: (a -> a -> Ordering) -> [a] -> [a]
First parameter of sortBy suggests that to compare elements we need a sorting predicate — a function which takes two elements of the list and tells if the first one is greater. In many cases, yours included, you don't have to define such a function by yourself. Instead, you can use a function which “measures” how important an element of a list is. E.g. you have an element of a list (x,y) and its measure is |x-y| — this is exactly your ab function, but remember that we want it to be defined via standard ones.
For now, we have two tasks: 1) define measure function of type (Int, Int) -> Int; 2) learn how to turn it into into a sorting predicate. I told that the the latter one is trivial, as it can be done via standard function comparing:
ghci> import Data.Ord
ghci> :t comparing
comparing :: Ord a => (b -> a) -> b -> b -> Ordering
So what I'm suggesting is that comparing ab is a perfect match for the first argument of sortBy. Not let's turn to the other task: defining ab via standard functions.
Consider the type of - function:
ghci> :t (-)
(-) :: Num a => a -> a -> a
If you substitute Int for the a(¹) you get nearly the type you want to have, i.e. Int -> Int -> Int. Here we hit very frequent task of turning a function from two arguments ((-)) into a function acting on pairs. Luckily, there is a standard function for doing this, namely, uncurry:
ghci> :t uncurry (-)
uncurry (-) :: Num c => (c, c) -> c
That's what we need! Now we just have to pipe it with the abs function which computes |·|, and we are good. We compose functions be means of .. Resulting solution is this one:
import Data.List (sortBy)
import Data.Ord (comparing)
sortAbsPairs :: [(Int,Int)] -> [(Int,Int)]
sortAbsPairs = sortBy (comparing $ abs . uncurry (-))
You can try it out in GHCi assuming you saved it in sort.hs:
ghci>:l sort.hs
Ok, one module loaded.
ghci> sortAbsPairs [(8,20), (5, 10), (1,2)]
[(1, 2), (5, 10), (8, 20)]
(¹) You actually can ask GHCi to substitute types for type parameters of functions by setting up a language extension called TypeApplications:
ghci> :set -XTypeApplications
ghci> :t (-) #Int
(-) #Int :: Int -> Int -> Int
While sortBy is well-known, it is mostly accompanied by comparing. You can use sortOn instead. sortOn has the advantage that it uses the Schwartzian transform, i.e. it only computes the difference once for each element.
--Prelude Data.List> :t sortOn
--sortOn :: Ord b => (a -> b) -> [a] -> [a]
import Data.List(sortOn)
sort = sortOn (abs . uncurry (-))
But if you really want to use your original sort, pattern match the pairs:
sort ((x,x'):xs) = [ (a,a') | (a,a') <- xs, -- ... your homework here
I extend the homework part at a later point to make it a full answer.

Understand and use the basic concept of Haskell's Integral typeclass

I'm taking a course which focuses on Haskell & Prolog and there's an upcoming test for which i'm studying.
We're given a signature:
myList
:: (Integral a)
=> [a]
And we have to create a variable myList which will return an infinite list which is different from standard positive integer list by changing the position of every third element by moving it two positions to the right, starting from the first one.
So for example, the beginning would look like:
2,3,1,5,6,4,8,9,7.. on a standard list which contains positive elements.
I tried to solve this with a code like this:
myList (x:y:z:xs)
= y:z:x:(myList(xs))
myList [] = []
myList [x] = [x]
It gives the result needed but it's not following the signature. Could someone explain how to solve it so it would fit the signature and why it does.
Thanks.
The function (the implementation of which you got perfectly right, as a matter of fact)
myList (x:y:z:xs) = y:z:x:(myList xs)
myList [] = []
myList [x] = [x]
is generic enough not to depend on the type of the elements in the list to be Integral a => a. So if you let Haskell infer its type, it will infer [a] -> [a]. If you constraint the type to Integral a => [a] -> [a], it will still work, but be less generic, which will limit uses to just integral types.
Here's a demonstration of the principle:
Prelude> :{
Prelude| let myList (x:y:z:xs) = y:z:x:(myList(xs))
Prelude| myList [] = []
Prelude| myList [x] = [x]
Prelude| :}
Prelude> :t myList
myList :: [a] -> [a]
Prelude> take 15 $ myList ['a'..]
"bcaefdhigkljnom"
Prelude> take 15 $ myList [1..]
[2,3,1,5,6,4,8,9,7,11,12,10,14,15,13]
but
Prelude> :{
Prelude| let myList :: Integral a => [a] -> [a]
Prelude| myList (x:y:z:xs) = y:z:x:(myList(xs))
Prelude| myList [] = []
Prelude| myList [x] = [x]
Prelude| :}
Prelude> :t myList
myList :: Integral a => [a] -> [a]
Prelude> take 15 $ myList [1..]
[2,3,1,5,6,4,8,9,7,11,12,10,14,15,13]
Prelude> take 15 $ myList ['a'..]
<interactive>:34:11:
No instance for (Integral Char) arising from a use of ‘myList’
In the second argument of ‘($)’, namely ‘myList ['a' .. ]’
In the expression: take 15 $ myList ['a' .. ]
In an equation for ‘it’: it = take 15 $ myList ['a' .. ]
So the point is, both definitions are equivalent and capable of doing the same thing just as well as the other, but the constrained type signature is (and I'd say unjustifiably) less useful than the one with the general type signature.
If the assignment demands a function of type Integral a => [a] -> [a], all you really need to do is simply annotate the function you already have with exactly that type signature. There is, however, no (reasonable/rational) way to somehow guide Haskell to infer that type from the function definition, as that would necessitate somehow indirectly indicating that the list must contain values of a type that support the operations in Integral ... yada yada.
As a final note: you got the implementation/algorithm perfectly right, but fell short on type signatures and the notion of generality.
EDIT: if what you actually need is not a function but a list (your question is a bit ambiguous in this respect), all you need to do is rename the below definition of myList to e.g. myList' or go (which I think is quite a typical name for nested recursive helpers) or something (which can but doesn't have to be an hidden within the list myList) and then pass [1..] to it, assigning the result to myList:
myList :: Integral a => [a]
myList = go [1..]
where go (x:y:z:xs) = y:z:x:(go xs)
go [] = []
go [x] = [x]
of course looked this way, Integral a => [a] is indeed quite general a signature for the list (but not the most general, which would be (Enum a, Num a) => [a] as I was led to realize by dfeuer's comment), because the type a cannot be determined by the type of the input passed to the function, because you're always passing [1..].
If we want to give an answer with the right signature without supplying any signatures by hand, we have to look at the Integral class and look which methods it implements. Applying any such method is likely to force the right signature.
Prelude> :i Integral
class (Real a, Enum a) => Integral a where
quot :: a -> a -> a
rem :: a -> a -> a
div :: a -> a -> a
mod :: a -> a -> a
quotRem :: a -> a -> (a, a)
divMod :: a -> a -> (a, a)
toInteger :: a -> Integer
Since our sequence has something to do with remainders of division by 3, div and mod look promising.
After some fiddling with arithmetic, we arrive at something like
Prelude> let myList = map (\x -> x - x `mod` 3 + (x+2) `mod` 3 + 1) [0..]
Prelude> :t myList
myList :: Integral b => [b]

GHC not deducing the way I would like it to :-(

chainQuery :: (Enum a, Integral a, Ord b) => a -> b -> [c]
chainQuery n min = map length $ filter beatingLength $ map chain [1..n]
where
beatingLength :: [a] -> Bool
beatingLength xs = length xs > min
chain :: (Integral a) => a -> [a]
chain n
| n <= 1 = [n]
| even n = n:(chain $ div n 2)
| otherwise = n:(chain $ n * 3 + 1)
In the code sample above why isn't GHC able to deduce that 'c' is an Int by looking at the type definition for length?
Why does GHC need to know anything about 'b' other than that it is an Ord?
Is there a better way to write this function?
GHC is able to infer [Int] as the result type for the function. The problem is that you've claimed in your type signature that it should be more polymorphic, that the result could be a list of any type, which does not make sense since the return value comes from the map length so it must have type [Int]. This is what GHC is complaining about when it says Could not deduce (c ~ Int).
You're comparing min to length xs. The greater-than operator has the type (>) :: (Ord a) => a -> a -> Bool, which means that both sides must be the same type. The type of length xs is Int, so this forces min to be Int as well.
Probably. For example, you can map the length before doing the filtering. This makes it easy to use an operator section instead of your beatingLength function. You can also move the parenthesis to save a use of $ to make the code a bit neater.
chainQuery n min = filter (> min) $ map (length . chain) [1..n]
where chain n | n <= 1 = [1]
| even n = n : chain (n `div` 2)
| otherwise = n : chain (3*n + 1)
For reference, the easiest way to solve a problem like this is to remove your type signature and see what type was inferred in GHCi using the :t command. In this case, the inferred type is
*Main> :t chainQuery
chainQuery :: Integral a => a -> Int -> [Int]

Resources