Why in this line of haskell, $ cannot replace () - haskell

The code is
prime (x:xs) = x:prime (filter (\y -> y `mod` x /=0) xs)
If I change it to
prime (x:xs) = x:prime $ filter (\y -> y `mod` x /=0) xs
There is a pattern matching error.

If I try to reproduce the error, it seems like GHC understands it like so:
(x : prime) $ filter (\y -> y `mod` x /= 0) xs
But you want it like that:
x : (prime $ filter (\y -> y `mod` x /= 0) xs)
So you just have to use bracket notation, I think.

First of all, it's a misconception that $ is a syntactic replacement for () — $ is a regular operator (which itself is a function that is simply infix by default); it's just the precedence rules that make $ convenient in many cases — but there's no syntactic magic behind it.
Now, ignoring the irrelevant bits, let's just concentrate on the part of the code that's causing the error:
x : prime (foo bar)
is the same as
x : (prime (foo bar))
because the : on the left has a lower precedence than the function application on the right.
However
x : prime $ foo bar
is the same as
(x : prime) $ (foo bar)
which is the same as
(x : prime) (foo bar)
because the : on the left has a higher precedence than the $ on the right.
So the error comes from the fact that you're trying to apply the result of the expression x : prime to the argument foo bar as if x : prime were a function, but it's not, hence the type error.
Solution? Either throw in some parentheses, or even better, don't use the $ at all in this case.

When you write:
x : prime $ filter foo xs
It is interpreted as
(x : prime) $ filter foo xs
due to (:) having a higher precedence than ($). See the fixity declarations section of this report for more.
It fails because a list of functions ((x:prime)) is not a function, and cannot be used as such.
If you want to make the function prettier, try this:
prime (x:xs) = x : prime (filter ((/= 0) . (`mod` x)) xs)

Others have already explained the problem. Here is one solution:
prime (x:xs) = (x:) $ prime $ filter (\y -> y `mod` x /=0) xs
That is, you can use an operator section to express the application of : to x and then apply the result as you like.

Related

What are the redexes in this Haskell expression?

I am learning Haskell for a university course and i have a question about reducible expressions (redexes). I understand the concept yet I still have some questions that I can't seem to figure out on my own.
Lets say you would want to find all the reducible expressions in an expression, like this:
head (map (+1) (3:repeat 3))
In this expression an obvious redex would be map (+1) (3:repeat 3)) because it matches to the definition of map, so Haskell would "reduce" the expression and map would increment the 3 and 4:map (+1) (repeat 3). would be reduced next.
The question I have is:
Is head (map (+1) (3:repeat 3)) already a redex, before map is evaluated?
Because the "input" of head does not match the constructor of a list (which is what head is looking for), I am confused about whether it still is a redex because logically it can't get reduced yet, but the definitions online seem to be saying that it would be.
Haskell's evaluation is lazy: it proceeds by topmost leftmost redex strategy (at least conceptually): it reduces the leftmost among the topmost redexes.
Presumably head is defined as
head xs = case xs of (x:_) -> x
so then its application to whatever expression is indeed a redex -- an expression in need of reducing. Which proceeds according to the definition of head,
head (map (+1) (3:repeat 3))
=
case (map (+1) (3:repeat 3)) of (x:_) -> x
=
(or we could say that head itself is the topmost leftmost redex, which reduces to its definition, first; and if we'd written the above as ((\xs -> case xs of (x:_) -> x) (map (+1) (3:repeat 3))) we'd get to the same outcome, just a bit more tediously).
A primary forcing primitive is case. Now it needs to perform the pattern match, so it must find out the value of its scrutinee expression (only to the extent that the pattern match becomes possible). To do that it must now work according to the definition of map which is presumably
map f xs = case xs of { (x:ys) -> f x : map f ys
; [] -> [] }
so it becomes
case (map (+1) (3:repeat 3)) of (x:_) -> x
=
case (case (3:repeat 3) of
{ (x:ys ) -> (+1) x : map (+1) ys
; [] -> [] } )
of (x:_) -> x
=
At this point the inner case expression can be reduced,
case (let { x=3 ; ys=repeat 3} in
(+1) x : map (+1) ys )
of (x : _ ) -> x
=
and now the outer case's pattern matching becomes possible,
case (let { x=3 } in
(+1) x )
of (x ) -> x
=
let { x=3 } in
(+1) x
=
(+1) 3
=
4

nubBy is not working as expected

The function below should generate prime numbers however it does not for GHC 7.10.2. Is anybody else seeing this?
GHCi, version 7.10.2: http://www.haskell.org/ghc/ :? for help
Prelude> import Data.List
Prelude Data.List> print . take 100 . nubBy (\x y -> x `rem` y == 0) $ [2..]
[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101]
The strange part is that it seems to work fine on this site:
rextester.com/LWZCQ71376
What changed between base-4.7.x and base-4.8.0.0 is the definition of elem_by which is what nubBy is defined in terms of.
In base-4.7 elem_by has this clause:
elem_by eq y (x:xs) = y `eq` x || elem_by eq y xs
and in base-4.8 it was changed to:
elem_by eq y (x:xs) = x `eq` y || elem_by eq y xs
The history of this change is documented in these TRAC issues:
2528
3280
7913
Note that the Haskell Report Prelude version of nubBy is:
nubBy eq (x:xs) = x : nubBy eq (filter (\ y -> not (eq x y)) xs)
which was at odds with the base-4.7 implementation, so that also explains the change.
The order of the arguments have been flipped, it seems, in the new base. EDIT: I called this a bug, but as another answer points out the old behavior was the incorrect order.
You can see the order has been flipped by observing:
> print . take 5 . nubBy (\x y -> trace (show (x,y)) $ x `rem` y == 0) $ [2..]
[2(2,3)
,3(3,4)
(2,4)
,4(4,5)
(3,5)
(2,5)
Certainly rem 2 4 does not equal zero (it equals 2), so it yields 4.
Notice you get the result you desire when you flip the argument order in the lambda:
> print . take 5 . nubBy (\x y -> trace (show (x,y)) $ y `rem` x == 0) $ [2..]
[2(2,3)
,3(3,4)
(2,4)
(3,5)
(2,5)
....
EDIT: Since discussion indicates the relation is supposed to be equality and operate regardless of the order (and I'm too lazy to look at the report right now) notice you can compare the arguments first and get stable behavior either way:
print . take 100 . nubBy (\x y -> rem (max x y) (min x y) == 0) $ [2..]

What is the Haskell way of solving this?

New to Haskell. I have the following code
fac :: Integer -> [Integer]
fac x = take 1 $ map (x `mod` ) $ reverse [2 .. xs]
where xs = floor $ sqrt $ fromIntegral x
I want to display the first value from [2 .. xs] such that x mod y == 0. But I can't use filter as that only would work off the output from mod. How do I do this?
You can use filter. Just compose (==0) and (x `mod`) for the first argument of filter.
If you are trying to do Project Euler Problem 3, this will be an incredibly painful way of solving it.
I would suggest the following:
Define a function for what you have in the where clause, i.e. isqrt = round . sqrt . fromIntegral
Define two functions isPrime and primeList that are mutually recursive for calculating primes and you should use isqrt in the definition of isPrime, although the use of the isqrt isn't actually necessary; I just find it easier to think about for writing this function. (there is a hint below for how to do this step)
Using primeList, define a recursive factorize function that outputs a list of primes (or something similar)
Factorize the number from the question and return the largest prime in the list
What I have suggested above is usually not that great for calculating very large primes quickly, but it should be adequate for this problem. This paper goes into more detail why: http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf
For future number theory related PE problems, look into using this library: https://hackage.haskell.org/package/arithmoi-0.2.0.4
Other comments:
Instead of take 1, you should actually use head; it's slightly better.
Also, since the biggest number you will deal with here is 600851475143, you don't actually need the function to have type Integer -> [Integer]. 32-bit Int doesn't do the trick, because maxBound :: Int is 2147483647. maxBound :: Int64, however, is 9223372036854775807, which is much more than you need. So you could just define your function to have type Int64 -> [Int64] (or just Int -> [Int] if the machine is 64-bit already).
Hint:
primeList should be defined as something like primeList = 2 : 3 : filter isPrime [5,7..], but you can decide to be as fancy as you want with this); again, these definitions should be mutually recursive.
I want to display the first value from [2 .. xs] such that x mod y == 0
In this case, you should not use reverse:
fac x = take 1 $ filter (\y -> x `mod` y == 0) $ reverse [2 .. xs]
where xs = floor $ sqrt $ fromIntegral x
If you want to find out the first value starting from xs such that mod x y == 0, there is also no need to use reverse:
fac x = take 1 $ filter (\y -> x `mod` y == 0) $ [xs, xs-1 .. 2]
where xs = floor $ sqrt $ fromIntegral x
fac x = take 1 $ filter (\y -> x `mod` y == 0 ) $ reverse [2 .. xs]
where xs = floor $ sqrt $ fromIntegral x
or, to be point-free:
fac x = take 1 $ filter ((== 0).(x `mod`)) $ reverse [2 .. xs]
where xs = floor $ sqrt $ fromIntegral x
Not sure if you want reverse here, or what exactly is your goal.
You can use filter. Here's a one-liner (well, two-liner if you count the import):
import Data.Ix (range)
fac x = head . filter ((==) 0 . mod x) . curry range 2 . floor . sqrt . fromIntegral $ x

Haskell: Double every 2nd element in list

I just started using Haskell and wanted to write a function that, given a list, returns a list in which every 2nd element has been doubled.
So far I've come up with this:
double_2nd :: [Int] -> [Int]
double_2nd [] = []
double_2nd (x:xs) = x : (2 * head xs) : double_2nd (tail xs)
Which works but I was wondering how you guys would write that function. Is there a more common/better way or does this look about right?
That's not bad, modulo the fixes suggested. Once you get more familiar with the base library you'll likely avoid explicit recursion in favor of some higher level functions, for example, you could create a list of functions where every other one is *2 and apply (zip) that list of functions to your list of numbers:
double = zipWith ($) (cycle [id,(*2)])
You can avoid "empty list" exceptions with some smart pattern matching.
double2nd (x:y:xs) = x : 2 * y : double2nd xs
double2nd a = a
this is simply syntax sugar for the following
double2nd xss = case xss of
x:y:xs -> x : 2 * y : double2nd xs
a -> a
the pattern matching is done in order, so xs will be matched against the pattern x:y:xs first. Then if that fails, the catch-all pattern a will succeed.
A little bit of necromancy, but I think that this method worked out very well for me and want to share:
double2nd n = zipWith (*) n (cycle [1,2])
zipWith takes a function and then applies that function across matching items in two lists (first item to first item, second item to second item, etc). The function is multiplication, and the zipped list is an endless cycle of 1s and 2s. zipWith (and all the zip variants) stops at the end of the shorter list.
Try it on an odd-length list:
Prelude> double_2nd [1]
[1,*** Exception: Prelude.head: empty list
And you can see the problem with your code. The 'head' and 'tail' are never a good idea.
For odd-lists or double_2nd [x] you can always add
double_2nd (x:xs) | length xs == 0 = [x]
| otherwise = x : (2 * head xs) : double_2nd (tail xs)
Thanks.
Here's a foldr-based solution.
bar :: Num a => [a] -> [a]
bar xs = foldr (\ x r f g -> f x (r g f))
(\ _ _ -> [])
xs
(:)
((:) . (*2))
Testing:
> bar [1..9]
[1,4,3,8,5,12,7,16,9]

Haskell, loading and is this merge function correct?

First off I am using ghci under ubuntu 11.10 to run the haskell code. 2nd this is my first attempts at haskell. Third, how might I load a file into ghci and where does it need to be located and what should its extension be? I know ":l "file.haskelxtnsn"" is how to load a file, but that's my best guess so far.
Seeing as I can do the above, how does this code look for merging two list of possibly infinite size in ascending order. (I can't put this in the prelude> prompt because of indentation???) Given [1, 2, 3] and [4, 5, 6] I should get [1, 2, 3, 4, 5, 6], and I think the usage would be "take 10 (merge listx listy)"
let merge x y = (min (head x) (head y)) :
case (min (head x) (head y)) of
head x -> merge (drop 1 x) y
head y -> merge x (drop 1 y)
psuedo:
output the min of the heads of the lists
if the first lists head was output call merge with the rest of the first list and the second
else call merge with the first list and the rest of the second list
Usually the extension used is ".hs".
You can use :cd in ghci to change directory, you can also supply a path to the :load (:l for short) command.
Your logic is correct, although maybe I'd write it a bit differently (hopefully you know about and where clause and defining a function as a series of equations):
merge [] ys = ys
merge xs [] = xs
merge xs ys = min x y : if x < y then merge (tail xs) ys
else merge xs (tail ys)
where x = head xs
y = head ys
In ghci you need a let in front of definitions, which is different from the let ... in ... expression. This is rather confusing so I suggest you just put your code in a file and load it in ghci.
Function application has higher precedence then the : operator, so some of you parenthesis is not needed. We usually try to minimize the number of parenthesis to make the code more concise, but don't be over zealous about it.
I don't really see the point of using a case expression here (other than causing an error). Try reading on pattern matching for more detail, data constructors vs function applications, why you can't use head x inside a pattern but you can do x:xs (Although I didn't here). Calling head and min multiple times looks redundant, andy ou can also substitute drop 1 with tail.
If you want to type this into the GHCi prompt, you can do it like this:
> let merge x y = (min (head x) (head y)) : case (min (head x) (head y)) of {
head x -> merge (drop 1 x) y ; head y -> merge x (drop 1 y) }
i.e. using explicit braces in place of indentation (all the above meant to be entered in one unbroken line). When putting the code into a file to be loaded, the leading let shouldn't be used.
As to the code itself, it causes an error "Parse error in pattern". This is because head x is not a valid pattern.
You can find a merge code e.g. here:
merge (x:xs) (y:ys) | y < x = y : merge (x:xs) ys
| otherwise = x : merge xs (y:ys)
merge xs [] = xs
merge [] ys = ys
This preserves duplicates.

Resources