Haskell xor not work for mapping - function

I have a problem of using xor function in Data.Bits module
like a code below
import Data.Bits
andFunc :: [Int] -> [Int] -> [Int]
andFunc xs ys = zipWith (\x y -> x .&. y) xs ys
xorFunc :: [Int] -> [Int] -> [Int]
xorFunc xs ys = zipWith (\x y -> x xor y) xs ys
When I try to apply andFunc with arguments of [1..10] and [2..11] (arguments are just arbitrary array)
it works. (Does not write here, but orFunc (.|.) also works)
but some reasons, xorFunc does not.... and says
<interactive>:74:1: error:
? Non type-variable argument
in the constraint: Enum ((a -> a -> a) -> t -> c)
(Use FlexibleContexts to permit this)
? When checking the inferred type
it :: forall a t c.
(Enum ((a -> a -> a) -> t -> c), Enum t,
Num ((a -> a -> a) -> t -> c), Num t, Bits a) =>
[c]
Do you know why?
Running Environment:
GHC 8.2.1 with no flags
Windows 10 64 bit

If you want to use functions in infix notation you have to use backtick syntax.
xorFunc :: [Int] -> [Int] -> [Int]
xorFunc xs ys = zipWith (\x y -> x `xor` y) xs ys
but this can be solved a bit simpler by not writing this as a lambda expression
xorFunc :: [Int] -> [Int] -> [Int]
xorFunc xs ys = zipWith xor xs ys
and applying eta reduce (twice), i.e. omitting parameters that are occurring in the last position and can be fully derived by the type checker.
xorFunc :: [Int] -> [Int] -> [Int]
xorFunc = zipWith xor

Infix functions are spelled with punctuation and can be made prefix with parentheses; e.g. x + y can also be spelled (+) x y. Going the other direction, prefix functions are spelled with letters and can be made infix with backticks; e.g. zip xs ys can also be spelled xs `zip` ys.
Applying that to your case, this means you should write one of xor x y or x `xor` y instead of x xor y.

xor is a regular function name, not an operator. You need to enclose it in backquotes to use as an infix operator.
xorFunc xs ys = zipWith (\x y -> x `xor` y) xs ys
That said, your lambda expressions aren't necessary; just use xor as argument to zip:
xorFunc xs ys = zipWith xor xs ys
or simply
xorFunc = zipWith xor
(Likewise, andFunc = zipWith (.&.); enclose the operator in parentheses to use it as a function value.)

Related

How to write my own Haskell sortOn function

I was wondering how to write my own sortOn function.
I made a sortBy function and an on function as shown bellow but can't figure out how to combine them and what additional code to add. sortOn is like sortBy but the given function (in here named comp) is applied only once for every element of the list
sortBy :: (a -> a -> Ordering) -> [a] -> [a]
sortBy comp [] = []
sortBy comp [x] = [x]
sortBy comp (x:xs) = insert x (sortBy comp xs)
where
insert x [] = [x]
insert x (y:ys)
| (comp x y == LT) || (comp x y == EQ) = x:y:ys
| otherwise = y:(insert x ys)
on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
on b f x y = b (f x) (f y)
Here's a hint.
If you have a list [a] and you just sort it, the sort function will implicitly make use of the Ord instance for a and specifically the function:
compare :: a -> a -> Ordering
to figure out the relative ordering of pairs of a elements.
Now, if you have a list [a] and a transformation function b, and you want to use sortOn to sort the list of the transformed values, you'll need to figure out the relative ordering of pairs of b elements. How will you do this? Well, you'll implicitly use the Ord instance for b and specifically the function:
compare :: b -> b -> Ordering
In other words, when you try to define:
sortOn :: (Ord b) => (a -> b) -> [a] -> [a]
sortOn f lst = ...
you'll have arguments of type:
f :: a -> b
lst :: [a]
and additional objects of type:
sortBy :: (a -> a -> Ordering) -> [a] -> [a]
on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
compare :: b -> b -> Ordering
Now, can you see how to put them together to define sortOn?
SPOILERS
Further hint: What's the type of compare `on` f?
Further further hint: It's a -> a -> Ordering.

Haskell: arrow precedence with function arguments

I'm a relatively experienced Haskell programmer with a few hours of experience, so the answer might be obvious.
After watching A taste of Haskell, I got lost when Simon explained how the append (++) function really works with its arguments.
So, here's the part where he talks about this.
First, he says that (++) :: [a] -> [a] -> [a] can be understood as a function which gets two lists as arguments, and returns a list after the last arrow). However, he adds that actually, something like this happens: (++) :: [a] -> ([a] -> [a]), the function takes only one argument and returns a function.
I'm not sure to understand how the returned function closure gets the first list as it expects one argument as well.
On the next slide of the presentation, we have the following implementation:
(++) :: [a] -> [a] -> [a]
[] ++ ys = ys
(x:xs) ++ ys = x : (xs ++ ys)
If I think that (++) receives two arguments and return a list, this piece of code along with the recursion is clear enough.
If we consider that (++) receives only one argument and returns a list, where does ys come from? Where is the returned function ?
The trick to understanding this is that all haskell functions only take 1 argument at most, it's just that the implicit parentheses in the type signature and syntax sugar make it appear as if there are more arguments. To use ++ as an example, the following transformations are all equivalent
xs ++ ys = ...
(++) xs ys = ...
(++) xs = \ys -> ...
(++) = \xs -> (\ys -> ...)
(++) = \xs ys -> ...
Another quick example:
doubleList :: [Int] -> [Int]
doubleList = map (*2)
Here we have a function of one argument doubleList without any explicit arguments. It would have been equivalent to write
doubleList x = map (*2) x
Or any of the following
doubleList = \x -> map (*2) x
doubleList = \x -> map (\y -> y * 2) x
doubleList x = map (\y -> y * 2) x
doubleList = map (\y -> y * 2)
The first definition of doubleList is written in what is commonly called point-free notation, so called because in the mathematical theory backing it the arguments are referred to as "points", so point-free is "without arguments".
A more complex example:
func = \x y z -> x * y + z
func = \x -> \y z -> x * y + z
func x = \y z -> x * y + z
func x = \y -> \z -> x * y + z
func x y = \z -> x * y + z
func x y z = x * y + z
Now if we wanted to completely remove all references to the arguments we can make use of the . operator which performs function composition:
func x y z = (+) (x * y) z -- Make the + prefix
func x y = (+) (x * y) -- Now z becomes implicit
func x y = (+) ((*) x y) -- Make the * prefix
func x y = ((+) . ((*) x)) y -- Rewrite using composition
func x = (+) . ((*) x) -- Now y becomes implicit
func x = (.) (+) ((*) x) -- Make the . prefix
func x = ((.) (+)) ((*) x) -- Make implicit parens explicit
func x = (((.) (+)) . (*)) x -- Rewrite using composition
func = ((.) (+)) . (*) -- Now x becomes implicit
func = (.) ((.) (+)) (*) -- Make the . prefix
So as you can see there are lots of different ways to write a particular function with a varying number of explicit "arguments", some of which are very readable (i.e. func x y z = x * y + z) and some which are just a jumble of symbols with little meaning (i.e. func = (.) ((.) (+)) (*))
Maybe this will help. First let's write it without operator notation which might be confusing.
append :: [a] -> [a] -> [a]
append [] ys = ys
append (x:xs) ys = x : append xs ys
We can apply one argument at a time:
appendEmpty :: [a] -> [a]
appendEmpty = append []
we could equivalently could have written that
appendEmpty ys = ys
from the first equation.
If we apply a non-empty first argument:
-- Since 1 is an Int, the type gets specialized.
appendOne :: [Int] -> [Int]
appendOne = append (1:[])
we could have equivalently have written that
appendOne ys = 1 : append [] ys
from the second equation.
You are confused about how Function Currying works.
Consider the following function definitions of (++).
Takes two arguments, produces one list:
(++) :: [a] -> [a] -> [a]
[] ++ ys = ys
(x:xs) ++ ys = x : (xs ++ ys)
Takes one argument, produces a function taking one list and producing a list:
(++) :: [a] -> ([a] -> [a])
(++) [] = id
(++) (x:xs) = (x :) . (xs ++)
If you look closely, these functions will always produce the same output. By removing the second parameter, we have changed the return type from [a] to [a] -> [a].
If we supply two parameters to (++) we get a result of type [a]
If we supply only one parameter we get a result of type [a] -> [a]
This is called function currying. We don't need to provide all the arguments to a function with multiple arguments. If we supply fewer then the total number of arguments, instead of getting a "concrete" result ([a]) we get a function as a result which can take the remaining parameters ([a] -> [a]).

Haskell function composition

I've defined a function f1 and f2,so that I can use at the and the function composition (fkomp), which is supposed to use f1 and f2 to calculate 2^x by every element in a given List.
f1 :: Int -> Int
f1 x = product (replicate x 2)
f2 :: (a -> b) -> [a] -> [b]
f2 f xs = [f x | x <- xs]
fkomp :: [Int] -> [Int]
fkomp xs = f2 f1 $ xs
It works,but the problem is,that i can't write my code with composition:
fkomp xs = f2.f1 $ xs
I've been typing every single combination but it doesn't work with composition.
Could someone lighten my path ?
Thanks a lot
Ok, let's look just at the types (it's like a puzzle - the types have to fit):
f1 :: Int -> Int
f2 :: (a -> b) -> [a] -> [b] = (a -> b) -> ([a] -> [b])
in order to compose the both you need ones co-domain to be the same as the others domain.
This is because the composition has type:
(.) :: (b -> c) -> (a -> b) -> a -> c
See the b has to fit ;)
So for your f1 and f2 you would need either Int ~ (a -> b) or Int ~ ([a] -> [b]) both of which are not working well (as you found out).
BUT you kind of have the ability to apply f1 to f2 as f1 just fits f2 first argument (as you have seen too) - so I am a bit confused why you even want to use composition here.
remarks
your functions are a bit strange - I think the usual way to write them would be
f1 x = 2 ^ x
f2 = map
or even
fkomp :: [Int] -> [Int]
fkomp = map (2^)
note that the last one is not function-composition but (just as your case) function-application: I apply the function (2^) :: Int -> Int to map :: (Int -> Int) -> [Int] -> [Int] and get a function of type [Int] -> [Int] as the result (if you check the types in GHCi you will see a more generic versions but I think this is a bit more clear)

How to concatenate list in map function - Haskell?

I have two functions:
fun1 :: Int -> [Int]
fun2 :: [Int] -> [Int]
fun2 accept Int list and apply fun1 to each element of this list with help map. But fun1 return [Int]. So, I have type conflict. How to solve my problem?
You likely want a combination of map and concat to achieve it. Assuming fun1 and fun2 are something like this:
fun1 :: Int -> [Int]
fun1 x = [x,x]
fun2 :: [Int] -> [Int]
fun2 = map (+ 1)
solution :: [Int] -> [Int]
solution xs = concat $ map fun1 (fun2 xs)
Or as suggested by #CarstenKonig, you can use concatMap
solution2 :: [Int] -> [Int]
solution2 xs = concatMap fun1 $ fun2 xs
which can be further simplified to:
solution2 :: [Int] -> [Int]
solution2 = concatMap fun1 . fun2
The ability to transform [[a]] to [a] is what make List (among other thing) a Monad.
Therefore you can use the do notation :
fun2 xs = do
x <- xs
fun1 x
which can the be rewritten fun2 xs = xs >>= fun1 or even better
fun2 = (>>= fun1)
Another way is with list comprehension. Mapping fun1 over the list xs is
fun2' xs = [ fun1 x | x <- xs ]
-- = map fun1 xs
-- = do x <- xs -- for each x in xs:
-- return (fun1 x) -- yield (fun1 x)
which indeed would have a different type than what you wanted.
To flatten it one step further we do
fun2 xs = [ y | x <- xs, y <- fun1 x ]
-- = concatMap fun1 xs
-- = do x <- xs -- for each x in xs:
-- y <- fun1 x -- for each y in (fun1 x):
-- return y -- yield y

Act on a `case` clause in Haskell

I'm attempting problem 11 of "99 Haskell Problems." The problem description is pretty much:
Write a function encodeModified that groups consecutive equal elements, then counts each group, and separates singles from runs.
For example:
Prelude> encodeModified "aaaabccaadeeee"
[Multiple 4 'a',Single 'b',Multiple 2 'c',
Multiple 2 'a',Single 'd',Multiple 4 'e']
Here's my working code:
module Batch2 where
import Data.List -- for `group`
data MultiElement a = Single a | Multiple Int a deriving (Show)
encodeModified :: (Eq a) => [a] -> [MultiElement a]
encodeModified = map f . group
where f xs = case length xs of 1 -> Single (head xs)
_ -> Multiple (length xs) (head xs)
I'd like to take out that pesky repeated (head xs) in the final two lines. I figured I could do so by treating the result of the case clause as a partially applied data constructor, as follows, but no luck:
encodeModified :: (Eq a) => [a] -> [MultiElement a]
encodeModified = map f . group
where f xs = case length xs of 1 -> Single
_ -> Multiple length xs
(head xs)
I also tried putting parenthese around the case clause itself, but to no avail. In that case, the case clause itself failed to compile (throwing an error upon hitting the _ symbol on the second line of the clause).
EDIT: this error was because I added a parenthesis but didn't add an extra space to the next line to make the indentation match. Thanks, raymonad.
I can also solve it like this, but it seems a little messy:
encodeModified :: (Eq a) => [a] -> [MultiElement a]
encodeModified = map (\x -> f x (head x)) . group
where f xs = case length xs of 1 -> Single
_ -> Multiple (length xs)
How can I do this?
The function application operator $ can be used to make this work:
encodeModified = map f . group
where f xs = case length xs of 1 -> Single
_ -> Multiple (length xs)
$ head xs
You could match on xs itself instead:
encodeModified :: (Eq a) => [a] -> [MultiElement a]
encodeModified = map f . group
where f xs = case xs of (x:[]) -> Single x
(x:_) -> Multiple (length xs) x
or more tersely as
encodeModified :: (Eq a) => [a] -> [MultiElement a]
encodeModified = map f . group
where f (x:[]) = Single x
f xs#(x:_) = Multiple (length xs) x
or even
encodeModified :: (Eq a) => [a] -> [MultiElement a]
encodeModified = map f . group
where f as#(x:xs) = case xs of [] -> Single x
_ -> Multiple (length as) x
Admittedly most of these have some repetition, but not of function application.
You could also go with let:
encodeModified :: (Eq a) => [a] -> [MultiElement a]
encodeModified = map f . group
where f xs = let x = head xs
len = length xs in
case len of 1 -> Single x
_ -> Multiple len x