Haskell - sum of cubes of a list - haskell

I have to write a function that sums the cubes of a list of numbers.
This is my code so far:
cube' :: (Num a) => a -> a
cube' x = x*x*x
mySum :: (Num a) => [a] -> a
mySum [] = []
mySum xs = foldr (\acc x -> acc + cube'(x)) 0 xs
The problem is that when I run it I get the following error:
No instance for (Num[t0]) arising from a use of 'it'
In a stmt of an interactive GHCI command: print it

You're definitely on the right track. As bhelkir points out in a comment, the first clause of the definition is wrong and unnecessary. The other problem is that you have the argument order wrong for the lambda.

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.

Remove first element that fulfills predicate (Haskell)

I want to make a function that removes the first element that fulfills the predicate given in the second argument. Something like this:
removeFirst "abab" (< 'b') = "bab"
removeFirst "abab" (== 'b') = "aab"
removeFirst "abab" (> 'b') = "abab"
removeFirst [1,2,3,4] even = [1,3,4]
I wanted to do it by recursively, and came up with this:
removeFirst :: [a] -> (a -> Bool) -> [a]
removeFirst [] _ = []
rremoveFirst (x:xs) p = if p x then x : removeFirst xs p else removeFirst xs p
(Inspired by this question)
But I get a type-error, like this:
Couldn't match type ‘a’ with ‘Bool’
Expected: [Bool]
Actual: [a]
‘a’ is a rigid type variable bound by
the type signature for:
removeFirst :: forall a. [a] -> (a -> Bool) -> [a]
or this:
ghci> removeFirst [1,2,3,4] even
<interactive>:25:1: error:
* Variable not in scope: removeFirst :: [a0] -> (a1 -> Bool) -> t
* Perhaps you meant `rem' (imported from Prelude)
I know this is a relatively simple thing to program, I am just not familiar enough with Haskell yet. How can I do this "Haskell-style" (in one line)?
Before doing it "in style", why not first simply do it, so it works. This is how we learn.
"Variable not in scope: removeFirst ..." simply means you haven't defined the function named removeFirst.
So it seems you first tried to define it (and the error you show does not go with the code you show), then you got errors so it didn't get defined, and then you tried calling it and got the error saying it's not defined yet, naturally.
So, save your program in a source file, then load that file in GHCi. Then if you get any errors please copy-paste the full code from your file into your question (do not re-type it by hand). Also please specify what is it you do when you get the error messages, precisely. And be sure to include the error messages in full by copy-pasting them as well.
Then the logic of your code can be addressed.
Since others have posted working code, here's how I'd code this as a one-liner of sorts:
remFirst :: [a] -> (a -> Bool) -> [a]
remFirst xs p = foldr g z xs xs
where
g x r ~(_:tl) -- "r" for recursive result
| p x -- we've found it, then
= tl -- just return the tail
| otherwise
= x : r tl -- keep x and continue
z _ = [] -- none were found
Shortened, it becomes
remFirst xs p =
foldr (\x r ~(_:tl) -> if p x then tl else x : r tl)
(const []) xs xs
Not one line, but it works.
removeFirst :: [a] -> (a -> Bool) -> [a]
removeFirst (x:xs) pred
| pred x = xs
| otherwise = x : removeFirst xs pred
For a one-liner, I imagine you'd want to use foldl to walk across the list from the left.
EDIT
This solution uses guards, it first checks to see if the first element of the list passed in satisfies the predicate, and if not, it prepends it to the list and recursively checks the tail of the passed in list.
Using manual recursion does not lead to a one-liner solution, so let's try using some pre-built recursion scheme from the library.
Function scanl :: (b -> a -> b) -> b -> [a] -> [b] looks handy. It produces a succession of states, one state per input item.
Testing under the ghci interpreter:
$ ghci
λ>
λ> p = (=='b')
λ>
λ> xs = "ababcdab"
λ> ss = tail $ scanl (\(s,n) x -> if (p x) then (x,n+1) else (x,n)) (undefined,0) xs
λ>
λ> ss
[('a',0),('b',1),('a',1),('b',2),('c',2),('d',2),('a',2),('b',3)]
λ>
At that point, it is easy to spot and get rid of the one unwanted element, thru some simple data massaging:
λ>
λ> filter (\(x,n) -> (n /= 1) || (not $ p x)) ss
[('a',0),('a',1),('b',2),('c',2),('d',2),('a',2),('b',3)]
λ>
λ> map fst $ filter (\(x,n) -> (n /= 1) || (not $ p x)) ss
"aabcdab"
λ>
Let's now write our removeFirst function. I take the liberty to have the predicate as leftmost argument; this is what all library functions do.
removeFirst :: (a -> Bool) -> [a] -> [a]
removeFirst p =
let
stepFn = \(s,n) x -> if (p x) then (x,n+1) else (x,n)
p2 = \(x,n) -> (n /= 1) || (not $ p x)
in
map fst . filter p2 . tail . scanl stepFn (undefined,0)
If required, this version can be changed into a one-liner solution, just by expanding the values of stepFn and p2 into the last line. Left as an exercise for the reader. It makes for a long line, so it is debatable whether that improves readability.
Addendum:
Another approach consists in trying to find a library function, similar to splitAt :: Int -> [a] -> ([a], [a]) but taking a predicate instead of the list position.
So we submit the (a -> Bool) -> [a] -> ([a],[a]) type signature into the Hoogle specialized search engine.
This readily finds the break library function. It is exactly what we require.
λ>
λ> break (=='b') "zqababcdefab"
("zqa","babcdefab")
λ>
So we can write our removeFirst function like this:
removeFirst :: (a -> Bool) -> [a] -> [a]
removeFirst p xs = let (ys,zs) = break p xs in ys ++ (tail zs)
The source code for break simply uses manual recursion.

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]

Haskell error No instance for (Floating Int)

This code is to get the distance between 2 points but i got a problem!
UPDATED by #EduardoLeon
rango2 :: Int -> [Int] -> [[Int]] -> [Int]
rango2 a b list = if (verif [(list!!a!!0),(list!!a!!1),(list!!a!!2)] (b)) then [1]
else [0]
verif :: [Int] -> [Int] -> Bool
verif a b = if ((distance a b) > a!!2) then True
else False
difference :: Num a => [a] -> [a] -> [a]
difference xs ys = zipWith (-) xs ys
dotProduct :: Num a => [a] -> [a] -> a
dotProduct xs ys = sum $ zipWith (*) xs ys
distance :: Floating a => [a] -> [a] -> a
distance xs ys = sqrt $ dotProduct zs zs
where
zs = difference xs ys
EDITED: I cant change Int to Float, because im doing operations with lists and now
throw this error!
Proyecto.hs:71:18:
No instance for (Floating Int) arising from a use of `distance'
Possible fix: add an instance declaration for (Floating Int)
In the first argument of `(>)', namely `(distance a b)'
In the expression: ((distance a b) > a !! 2)
In the expression:
if ((distance a b) > a !! 2) then True else False
To answer your concrete question: Unlike more conventional languages, Haskell does not automatically cast integers to floats. In fact, the very notion of casting does not exist in Haskell. You need to use the function fromIntegral to convert integers to other numeric types. You could try the following in ghci:
> let x = 5 :: Integer
> sqrt x
<interactive>:3:1:
No instance for (Floating Integer) arising from a use of `sqrt'
In the expression: sqrt x
In an equation for `it': it = sqrt x
> let y = fromIntegral x :: Double
> sqrt y
2.23606797749979
I would also like to make some other suggestions regarding your coding style:
Decompose your functions into smaller functions that do exactly one thing and do it well.
The function (!!) traverses a linked list to find the n-th element. This is an O(n) operation, which is more expensive than necessary if you intend to retrieve multiple elements from the same list. Prefer solutions that avoid traversing the same list more than once.
Here is how I would find the distance between two points:
difference :: Num a => [a] -> [a] -> [a]
difference xs ys = zipWith (-) xs ys
dotProduct :: Num a => [a] -> [a] -> a
dotProduct xs ys = sum $ zipWith (*) xs ys
distance :: Floating a => [a] -> [a] -> a
distance xs ys = sqrt $ dotProduct zs zs
where
zs = difference xs ys
I was searching and i saw that i need to change Int to Float?
Just change the type signature to Float and things will start working:
verif :: [Float] -> [Float] -> Bool
You need to change the type signature of your code to indicate that it works with floating data since sqrt function operates on that. A more generic solution would be this:
verif :: (Floating a, Ord a) => [a] -> [a] -> Bool
verif a b = if (sqrt((((b!!0)-(a!!0))*((b!!0)-(a!!0)))+(((b!!1)-(a!!1))*((b!!1)-(a!!1)))) < a!!3)
then True
else if (sqrt((((b!!0)-(a!!0))*((b!!0)-(a!!0)))+(((b!!1)-(a!!1))*((b!!1)-(a!!1)))) == a!!3)
then True
else False
The use of the !! function isn't encouraged in Haskell. I would suggest you to rewrite the function in a more functional way.
I suggest that you revisit your design. What are the meanings of the lists a and b in verif? It looks like you are finding the distance between two points. You can create a type:
data Point = Point Double Double
and a function
distance :: Point -> Point -> Double
to make your code much more readable.
This should also eliminate doing the same calculation twice by using a where clause or let binding.

Haskell beginner query

Hi I have a query about a simple haskell definition. I have a definition but I don't fully understand it.
The function takes in a list of functions and an item and returns a list formed by applying that function.
applyAll = \fs -> \x -> map(\n -> n x) fs
Could somebody explain what n does and why is fs outside the map function?
The spacing is misleading you. It looks like map(\n -> n x) is a function call, but the parentheses here are for grouping, not function call. map takes two arguments; the full call is map (\n -> n x) fs, where (\n -> n x) is the first argument (a lambda expression) and fs is the second.
The lambda \n -> n x is a function that takes a function as an argument and returns the result of applying that function to x. n is the argument here. The type of \n -> n x is (a -> b) -> b (where a is the type of x). If you have learned about sections yet, the lambda is equivalent to the section ($ x). If you haven't, ignore that last sentence.
The function definition:
applyAll = \fs -> \x -> map(\n -> n x) fs
is the same as:
applyAll fs x = map(\n -> n x) fs
Now you might ask, "What are those ->s doing there if they are just arguments to my function applyAll. Haskell has no concept of multi-param functions. What you see as multiple arguments to a function is just many functions chained together each with a single argument. In the case of applyAll, it's just two functions chained together:
(applyAll fs) -> x = map (\n -> n x) fs
applyAll fs is one function chained to another argument identified as x to yield a list of values returned by map.
I could try this out in ghci:
Prelude> :t applyAll
applyAll :: [t -> b] -> t -> [b]
Prelude> :t applyAll xs
<interactive>:1:10: Not in scope: `xs'
Prelude> let xs = [1..5]
-- hah, BOOM! I told you haskell's strongly typed...
Prelude> :t applyAll xs
<interactive>:1:10:
Couldn't match expected type `t0 -> b0' with actual type `Integer'
Expected type: [t0 -> b0]
Actual type: [Integer]
In the first argument of `applyAll', namely `xs'
In the expression: applyAll xs
Prelude> let xs = [(1 +), (2 +), (3 *), (4 /)]
Prelude> :t xs
xs :: [Double -> Double]
Prelude> :t applyAll xs
applyAll xs :: Double -> [Double]
Prelude> :t applyAll
applyAll :: [t -> b] -> t -> [b]
Prelude> :t applyAll xs 3
applyAll xs 3 :: [Double]
Prelude> applyAll xs 3
[4.0,5.0,9.0,1.3333333333333333]
What's the type of map?
map :: (a -> b) -> [a] -> [b]
This tells me that map takes a function - let's call it f and a list of values to return another list of values. The function f is one that takes a value of type a returning another of type b. So map goes on applying f to each value in the list [a] to return another list filled with values of type b.
In your applyAll, the function f is \n -> n x. This is a lambda expression(you might call it an anonymous function) taking a value identified by n and applying x to it. This goes on for every item in the input list identified by [a] in the type definition until it runs out to yield another list identified by [b] in the type definition.
Here's a simple function definition:
f x = 2*x + 1
This creates a new function f, which takes one argument. You could use it later like this:
main = print (f 3)
...which would print 7. Sometimes, it is convenient to define a function without giving it a name. The syntax for that is \{- argument -} -> {- function body -}; for example, we could do an anonymous version of f above this way:
main = print ((\x -> 2*x + 1) 3)
Now, your definition of applyAll is just doing this several times. We could explicitly name everything in where clauses if we wanted:
applyAll = outerMost where
outerMost fs = mapApply where
mapApply x = map applyToX fs where
applyToX n = n x
...though I think you'll agree that the extra verbosity doesn't make things much more clear! A more natural (but less mechanical) translation away from anonymous functions would look like this:
applyAll fs x = map applyToX fs where
applyToX n = n x
and now hopefully this can very nearly read like English: to apply all the functions fs to a single value x, we map "the function that applies a single function (which we temporarily name n) to the value x" over the list of all functions.

Resources