Haskell filter operation with modulo - haskell

I'm trying to use the "filter" from Haskell but I've got stuck.
I wanna use the filter and modulo together in one function like this
multipleOf7 :: [Int] -> [Int]
multipleOf7 x = filter (test) x
where test = x mod 7 == 0
I also tried to use the mod but it doesn't work.

You should have written mod using backquote
x `mod` 7 == 0
or use it normally
mod x 7 == 0
In haskell you can use any function as infix.
If you define a simple function like
myFunction x y = x * y
then if you want you can use it like:
z = 40 `myFunction` 50
if you want you can also define function with an infix style.
x `myFunction` y = x * y
that would be strictly the same, and you would still be able to call it the other way also:
z = myFunction 40 50
Moreover, in the same spirit, you can easily define custom infix operators/symbols in Haskell. For example:
(-!!->) a b = (a,b)
-- or identically, but no need for backticks for infix operators
a -!!-> b = (a,b)
that can be used this way:
c = 1 -!!-> 2
-- and now c == (1,2)
but this should be used sparingly, choose your custom symbol carefully, and with the clear intent of readability IMHO.

What you have to understand is that Haskell has a "very" uniform syntax (not that much "special" cases). You call a function f with arguments x y with f x y. Now mod is just an ordinary function like all other functions. So you should call it with:
mod x 7
You can also use backtics to call a binary operator with the function in between like:
x `mod` 7
So you can fix the problem with:
multipleOf7 :: [Int] -> [Int]
multipleOf7 x = filter (test) x
where test x = mod x 7 == 0
or more cleaner:
multipleOf7 :: [Int] -> [Int]
multipleOf7 = filter test
where test x = mod x 7 == 0
You can also rewrite the test function such that:
test = (0 ==) . flip mod 7
or make a shorter filter like:
multipleOf7 :: Integral b => [b] -> [b]
multipleOf7 = filter ((0 ==) . flip mod 7)
(opinion) In my personal opinion it is indeed weird at first to see mod x 7. But after a while you start to find this useful since it saves a lot of brain cycles not taking complicated syntax/grammar rules into account.

Since filter :: (a -> Bool) -> [a] -> [a] and in your case a = Int,
multipleOf7 :: [Int] -> [Int]
multipleOf7 ns = filter f ns
where
f :: Int -> Bool
f i = i `mod` 7 == 0
Like Willem Van Onsem, I would probably loosen the Int into an Integral a => a, since the library function mod :: Integral a => a -> a -> a is just as general. I would also parameterize the 7 into an n, ditch the ns and write the f as a lambda:
multipleOf :: Integral a => a -> [a] -> [a]
multipleOf n = filter (\i -> i `mod` n == 0)
Willem Van Onsem then rewrites it into pointfree style:
multipleOf7 :: Integral a => [a] -> [a]
multipleOf7 = filter ((0 ==) . flip mod 7)
Pointfree style is sometimes more readable. I'd argue that this isn't the case here. Another variation is available here,
multipleOf :: Integral a => a -> [a] -> [a]
multipleOf n = filter ((== 0) . (`mod` n))
Still, I like the first versions with where or a lambda better.

Related

length of list using foldr in haskell

I wrote the following code to calculate length of a list using foldr in haskell. When I compile the code it gives me error as "myfoldr.hs:3:1: parse error on input `where'". Can anyone please tell me what thing I might be missing or doing wrong in this code ?
mylength :: [Int] -> Int
mylength l = foldr f 0 l
where
f :: Int -> Int -> Int
f x y = y+1
In Haskell, whitespace matters - look at the guide on the Haskell wiki.
Formatting your code more correctly gives:
mylength :: [Int] -> Int
mylength l = foldr f 0 l
where
f :: Int -> Int -> Int
f x y = y + 1
Which works perfectly (although the argument x to f is a bit redundant, you might want to write it as f _ y = y + 1 instead, or use a lambda expression like foldr (\_ x -> x + 1) 0 l).
This is an indentation error: you have to indent the where clause, since otherwise Haskell will see the definition of f as a separate function. So we can fix it with:
mylength :: [Int] -> Int
mylength l = foldr f 0 l
where f :: Int -> Int -> Int
f x y = y+1
Nevertheless we can still make it more generic: instead of defining it for an [Int] list, we can define it over an [a] list, with:
mylength :: [a] -> Int
mylength l = foldr f 0 l
where f x y = y+1
We can also rewrite f as const (+1), so:
mylength :: Num n => [a] -> n
mylength = foldr (const (1+)) 0
Note that we can apply an eta-reduction here: remove l both in the head and the body of the mylength definition. Or in case we know that the number is also enumerable, we can use succ instead of (1+):
mylength :: (Enum n, Num n) => [a] -> n
mylength = foldr (const succ) 0

Product of 2 list haskell

I have 2 lists, x and y, I must calculate the product of
(xi^2 - yi^2 + 2*xi*yi) with xi from x
and yi from y
List x = [2,4,5,6,8] xi = 2/3/...
List y = [7,3,4,59,0] yi = 7/3/4...
It's a bit tricky because I can use only functions without the product function without recursion and list comprehension.
prod :: [Int] -> [Int] -> Int
I would write the product function myself:
product :: [Integer] -> Integer
product [] = 1
product i f = foldl (*) 1 [i..f]
But I don't know how to apply it to the both strings.
Well you can define a product yourself with foldl :: (b -> a -> b) -> b -> [a] -> [b] like:
ownProduct :: Num b => [b] -> b
ownProduct = foldl (*) 1
Because a foldl starts with the initial value (1) and applies that value to the first element of the list. The result of that operation is applied to the function again but now with the second element of that list and so on until we reach the end. So foldl (*) 1 [x1,x2,...,xn] is equal to (((1*x1)*x2)*...)*xn.
Furthermore you can use a zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] function to convert two streams (one of as and one of bs) into a stream of c by applying the function element-wise.
So you can implement it like:
twoListProduct :: Num b => [b] -> [b] -> b
twoListProduct x y = foldl (*) 1 $ zipWith helper x y
where helper xi yi = xi*xi - yi*yi + 2*xi*yi
Allow me to reuse the excelent answer of #WillemVanOnsem in a more step-by-step aproach:
First, you must join the two list somehow. zip :: [a] -> [b] -> [(a,b)] is a handy function for doing this, from two list it returns a list of pairs.
zip [2,4,5,6,8] [7,3,4,59,0]
> [(2,7),(4,3),(5,4),(6,59),(8,0)]
Now, you must do your work with the pairs. Lets define de function you must apply to a pair:
squareB :: (Integer,Integer) -> Integer
squareB (x,y) = x^2 - y^2 + 2*x*y
Lets use map for aplying the square of a binomial function to each pair:
multiplicands:: [Integer] -> [Integer] -> [Integer]
multiplicands xs1 xs2 = map squareB (zip xs1 xs2)
For example:
multiplicands [2,4,5,6,8] [7,3,4,59,0]
>[-17,31,49,-2737,64]
Now, lets fold them from the left using (*) with base case 1, ie: (((1 * x1) * x2) .... xn):
solution :: [Integer] -> [Integer] -> Integer
solution xs1 xs2 = foldl (*) 1 (multiplicands xs1 xs2)
Lets check this function:
solution [2,4,5,6,8] [7,3,4,59,0]
> 452336326
with Willems' function:
twoListProduct [2,4,5,6,8] [7,3,4,59,0]
> 4523363264
You may also do as follows;
quadratics :: Num a => Int -> [a] -> [a] -> a
quadratics i ns ms = ((\(f,s) -> f*f + 2*f*s - s*s) . head . drop i . zip ns) ms
*Main> quadratics 0 [2,4,5,6,8] [7,3,4,59,0]
-17
*Main> quadratics 3 [2,4,5,6,8] [7,3,4,59,0]
-2737

haskell function that sums AND multiplies numbers of a list

I'm trying to do a function that given an operator and a function will go through a list like such:
reduce (*) even [1,2,3,4,5] => 8
reduce (+) odd [1,2,3,4,5] => 9
At first I had something like this:
reduce :: (Int-> Int-> Int) -> (Int->Bool) -> [Int] -> Int
reduce op x y = foldl op 1 (filter x y)
and it worked fine for multiplying, but added one number when trying to do a sum. So I thought of adding an if:
reduce :: (Int-> Int-> Int) -> (Int->Bool) -> [Int] -> Int
reduce op x y =
if op == (*) then foldl op 1 (filter x y)
else if op == (+) then foldl op 0 (filter x y)
else 0
However when I do this I get the following error:
Instance of Eq (Int -> Int -> Int) required for definition of reduce
What does it mean exactly? Any ideas? Thanks in advance
It means that with your current imports you cannot compare functions for equality (and even with suitable imports, there is no really good way to do the equality you ask for).
One simple solution is to demand that the user provide both the operation and the unit, thus:
reduce op u x y = foldl op u (filter x y)
In many cases of interest, there is already a Monoid instance that specifies the operator and unit. For example, there are the Sum and Product instances, so you might consider writing
reduce inject p = foldMap inject . filter p
which would be used like this:
> reduce Sum even [1..5]
Sum {getSum = 6}
> reduce Product odd [1..5]
Product {getProduct = 15}
What does it mean exactly? Any ideas? Thanks in advance
You're trying to compare some (Int -> Int -> Int) to another one. But functions cannot get checked on equality. Provide the initial value instead:
reduce :: (Int -> Int -> Int) -> (Int -> Bool) -> Int -> [Int] -> Int
reduce op f x xs = foldl op x (filter f xs)
By the way, you can generalize your function's type:
reduce :: (b -> a -> b) -> (a -> Bool) -> b -> [a] -> a
reduce op f x xs = foldl op x (filter f xs)
Alternatively, use a monoid and foldMap.

Project Euler 3 - Haskell

I'm working my way through the Project Euler problems in Haskell. I have got a solution for Problem 3 below, I have tested it on small numbers and it works, however due to the brute force implementation by deriving all the primes numbers first it is exponentially slow for larger numbers.
-- Project Euler 3
module Main
where
import System.IO
import Data.List
main = do
hSetBuffering stdin LineBuffering
putStrLn "This program returns the prime factors of a given integer"
putStrLn "Please enter a number"
nums <- getPrimes
putStrLn "The prime factors are: "
print (sort nums)
getPrimes = do
userNum <- getLine
let n = read userNum :: Int
let xs = [2..n]
return $ getFactors n (primeGen xs)
--primeGen :: (Integral a) => [a] -> [a]
primeGen [] = []
primeGen (x:xs) =
if x >= 2
then x:primeGen (filter (\n->n`mod` x/=0) xs)
else 1:[2]
--getFactors
getFactors :: (Integral a) => a -> [a] -> [a]
getFactors n xs = [ x | x <- xs, n `mod` x == 0]
I have looked at the solution here and can see how it is optimised by the first guard in factor. What I dont understand is this:
primes = 2 : filter ((==1) . length . primeFactors) [3,5..]
Specifically the first argument of filter.
((==1) . length . primeFactors)
As primeFactors is itself a function I don't understand how it is used in this context. Could somebody explain what is happening here please?
If you were to open ghci on the command line and type
Prelude> :t filter
You would get an output of
filter :: (a -> Bool) -> [a] -> [a]
What this means is that filter takes 2 arguments.
(a -> Bool) is a function that takes a single input, and returns a Bool.
[a] is a list of any type, as longs as it is the same type from the first argument.
filter will loop over every element in the list of its second argument, and apply it to the function that is its first argument. If the first argument returns True, it is added to the resulting list.
Again, in ghci, if you were to type
Prelude> :t (((==1) . length . primeFactors))
You should get
(((==1) . length . primeFactors)) :: a -> Bool
(==1) is a partially applied function.
Prelude> :t (==)
(==) :: Eq a => a -> a -> Bool
Prelude> :t (==1)
(==1) :: (Eq a, Num a) => a -> Bool
It only needs to take a single argument instead of two.
Meaning that together, it will take a single argument, and return a Boolean.
The way it works is as follows.
primeFactors will take a single argument, and calculate the results, which is a [Int].
length will take this list, and calculate the length of the list, and return an Int
(==1) will
look to see if the values returned by length is equal to 1.
If the length of the list is 1, that means it is a prime number.
(.) :: (b -> c) -> (a -> b) -> a -> c is the composition function, so
f . g = \x -> f (g x)
We can chain more than two functions together with this operator
f . g . h === \x -> f (g (h x))
This is what is happening in the expression ((==1) . length . primeFactors).
The expression
filter ((==1) . length . primeFactors) [3,5..]
is filtering the list [3, 5..] using the function (==1) . length . primeFactors. This notation is usually called point free, not because it doesn't have . points, but because it doesn't have any explicit arguments (called "points" in some mathematical contexts).
The . is actually a function, and in particular it performs function composition. If you have two functions f and g, then f . g = \x -> f (g x), that's all there is to it! The precedence of this operator lets you chain together many functions quite smoothly, so if you have f . g . h, this is the same as \x -> f (g (h x)). When you have many functions to chain together, the composition operator is very useful.
So in this case, you have the functions (==1), length, and primeFactors being compose together. (==1) is a function through what is called operator sections, meaning that you provide an argument to one side of an operator, and it results in a function that takes one argument and applies it to the other side. Other examples and their equivalent lambda forms are
(+1) => \x -> x + 1
(==1) => \x -> x == 1
(++"world") => \x -> x ++ "world"
("hello"++) => \x -> "hello" ++ x
If you wanted, you could re-write this expression using a lambda:
(==1) . length . primeFactors => (\x0 -> x0 == 1) . length . primeFactors
=> (\x1 -> (\x0 -> x0 == 1) (length (primeFactors x1)))
Or a bit cleaner using the $ operator:
(\x1 -> (\x0 -> x0 == 1) $ length $ primeFactors x1)
But this is still a lot more "wordy" than simply
(==1) . length . primeFactors
One thing to keep in mind is the type signature for .:
(.) :: (b -> c) -> (a -> b) -> a -> c
But I think it looks better with some extra parentheses:
(.) :: (b -> c) -> (a -> b) -> (a -> c)
This makes it more clear that this function takes two other functions and returns a third one. Pay close attention the the order of the type variables in this function. The first argument to . is a function (b -> c), and the second is a function (a -> b). You can think of it as going right to left, rather than the left to right behavior that we're used to in most OOP languages (something like myObj.someProperty.getSomeList().length()). We can get this functionality by defining a new operator that has the reverse order of arguments. If we use the F# convention, our operator is called |>:
(|>) :: (a -> b) -> (b -> c) -> (a -> c)
(|>) = flip (.)
Then we could have written this as
filter (primeFactors |> length |> (==1)) [3, 5..]
And you can think of |> as an arrow "feeding" the result of one function into the next.
This simply means, keep only the odd numbers that have only one prime factor.
In other pseodo-code: filter(x -> length(primeFactors(x)) == 1) for any x in [3,5,..]

Transforming a function that computes a fixed point

I have a function which computes a fixed point in terms of iterate:
equivalenceClosure :: (Ord a) => Relation a -> Relation a
equivalenceClosure = fst . List.head -- "guaranteed" to exist
. List.dropWhile (uncurry (/=)) -- removes pairs that are not equal
. U.List.pairwise (,) -- applies (,) to adjacent list elements
. iterate ( reflexivity
. symmetry
. transitivity
)
Notice that we can abstract from this to:
findFixedPoint :: (a -> a) -> a -> a
findFixedPoint f = fst . List.head
. List.dropWhile (uncurry (/=)) -- dropWhile we have not reached the fixed point
. U.List.pairwise (,) -- applies (,) to adjacent list elements
. iterate
$ f
Can this function be written in terms of fix? It seems like there should be a transformation from this scheme to something with fix in it, but I don't see it.
There's quite a bit going on here, from the mechanics of lazy evaluation, to the definition of a fixed point to the method of finding a fixed point. In short, I believe you may be incorrectly interchanging the fixed point of function application in the lambda calculus with your needs.
It may be helpful to note that your implementation of finding the fixed-point (utilizing iterate) requires a starting value for the sequence of function application. Contrast this to the fix function, which requires no such starting value (As a heads up, the types give this away already: findFixedPoint is of type (a -> a) -> a -> a, whereas fix has type (a -> a) -> a). This is inherently because the two functions do subtly different things.
Let's dig into this a little deeper. First, I should say that you may need to give a little bit more information (your implementation of pairwise, for example), but with a naive first-try, and my (possibly flawed) implementation of what I believe you want out of pairwise, your findFixedPoint function is equivalent in result to fix, for a certain class of functions only
Let's take a look at some code:
{-# LANGUAGE RankNTypes #-}
import Control.Monad.Fix
import qualified Data.List as List
findFixedPoint :: forall a. Eq a => (a -> a) -> a -> a
findFixedPoint f = fst . List.head
. List.dropWhile (uncurry (/=)) -- dropWhile we have not reached the fixed point
. pairwise (,) -- applies (,) to adjacent list elements
. iterate f
pairwise :: (a -> a -> b) -> [a] -> [b]
pairwise f [] = []
pairwise f (x:[]) = []
pairwise f (x:(xs:xss)) = f x xs:pairwise f xss
contrast this to the definition of fix:
fix :: (a -> a) -> a
fix f = let x = f x in x
and you'll notice that we're finding a very different kind of fixed-point (i.e. we abuse lazy evaluation to generate a fixed point for function application in the mathematical sense, where we only stop evaluation iff* the resulting function, applied to itself, evaluates to the same function).
For illustration, let's define a few functions:
lambdaA = const 3
lambdaB = (*)3
and let's see the difference between fix and findFixedPoint:
*Main> fix lambdaA -- evaluates to const 3 (const 3) = const 3
-- fixed point after one iteration
3
*Main> findFixedPoint lambdaA 0 -- evaluates to [const 3 0, const 3 (const 3 0), ... thunks]
-- followed by grabbing the head.
3
*Main> fix lambdaB -- does not stop evaluating
^CInterrupted.
*Main> findFixedPoint lambdaB 0 -- evaluates to [0, 0, ...thunks]
-- followed by grabbing the head
0
now if we can't specify the starting value, what is fix used for? It turns out that by adding fix to the lambda calculus, we gain the ability to specify the evaluation of recursive functions. Consider fact' = \rec n -> if n == 0 then 1 else n * rec (n-1), we can compute the fixed point of fact' as:
*Main> (fix fact') 5
120
where in evaluating (fix fact') repeatedly applies fact' itself until we reach the same function, which we then call with the value 5. We can see this in:
fix fact'
= fact' (fix fact')
= (\rec n -> if n == 0 then 1 else n * rec (n-1)) (fix fact')
= \n -> if n == 0 then 1 else n * fix fact' (n-1)
= \n -> if n == 0 then 1 else n * fact' (fix fact') (n-1)
= \n -> if n == 0 then 1
else n * (\rec n' -> if n' == 0 then 1 else n' * rec (n'-1)) (fix fact') (n-1)
= \n -> if n == 0 then 1
else n * (if n-1 == 0 then 1 else (n-1) * fix fact' (n-2))
= \n -> if n == 0 then 1
else n * (if n-1 == 0 then 1
else (n-1) * (if n-2 == 0 then 1
else (n-2) * fix fact' (n-3)))
= ...
So what does all this mean? depending on the function you're dealing with, you won't necessarily be able to use fix to compute the kind of fixed point you want. This is, to my knowledge, dependent on the function(s) in question. Not all functions have the kind of fixed point computed by fix!
*I've avoided talking about domain theory, as I believe it would only confuse an already subtle topic. If you're curious, fix finds a certain kind of fixed point, namely the least available fixed point of the poset the function is specified over.
Just for the record, it is possible to define the function findFixedPoint using fix.
As Raeez has pointed out, recursive functions can be defined in terms of fix.
The function that you are interested in can be recursively defined as:
findFixedPoint :: Eq a => (a -> a) -> a -> a
findFixedPoint f x =
case (f x) == x of
True -> x
False -> findFixedPoint f (f x)
This means that we can define it as fix ffp where ffp is:
ffp :: Eq a => ((a -> a) -> a -> a) -> (a -> a) -> a -> a
ffp g f x =
case (f x) == x of
True -> x
False -> g f (f x)
For a concrete example, let us assume that f is defined as
f = drop 1
It is easy to see that for every finite list l we have findFixedPoint f l == [].
Here is how fix ffp would work when the "value argument" is []:
(fix ffp) f []
= { definition of fix }
ffp (fix ffp) f []
= { f [] = [] and definition of ffp }
[]
On the other hand, if the "value argument" is [42], we would have:
fix ffp f [42]
= { definition of fix }
ffp (fix ffp) f [42]
= { f [42] =/= [42] and definition of ffp }
(fix ffp) f (f [42])
= { f [42] = [] }
(fix ffp) f []
= { see above }
[]

Resources