map and/or filter to only return a single element instead of list. HASKELL - haskell

The following function can use ONLY map and/or filter. No fold/foldr etc. The function should have the following signature and types: apply::n f x and it should apply f to x only n times. A bit more formally described, it looks like so: apply n f x = f (f...(f x)...), where f is applied n times.
This is very easily achievable with map, but the problem is that map will take and return a list. And I want it to only take a single integer, transform it by f and then return that new integer.
I so far wrote this: (works by taking and returning a list)
apply::Int->(Int->Int)->[Int]->[Int]
apply n f x
| n==1 =map f x
| n>1 =apply (n-1) f (map f x)
| otherwise =x
This is how I am calling it:
main = do
print(apply 2 (*2) [3])
How can I modify this function, s.t it no longer takes and returns a list, but instead takes a single integer and returns the new modified integer? Thanks

You don't need map or filter for this. If you enter the realm of the list monad, there's no escape (if you can only use filter and map). Here's a very simple implementation you can study on:
apply :: Int -> (a -> a) -> a -> a
apply 0 _ = id
apply 1 f = f
apply n f = (apply (n - 1) f) . f
Live demo

apply 0 _ x = x
apply 1 f x = f x
apply 2 f x = apply 1 (fmap f f) x
apply 3 f x = apply 1 (fmap f f) $ f x
apply 4 f x = apply 2 (fmap f f) x
apply 5 f x = apply 2 (fmap f f) $ f x
See if you can generalize.
Pro tips:
forall f. x = apply 0 (fmap f f) x and f x = apply 0 (fmap f f) $ f x
If f . g is well-typed, then fmap f g = f . g.
Not sure why you need map / filter; perhaps rephrase the question?

Related

Need help understanding Haskell id function

Hello I have two versions of this function and I am having some trouble.
iter :: Int -> (a -> a) -> (a -> a)
iter n f
| n > 0 = f . iter (n-1) f
| otherwise = id
iter' :: Int -> (a -> a) -> (a -> a)
iter' n = foldr (.) id . replicate n
I cannot understand even after googling what does id actually do here.
Like for example if we come to the function with n = 3 and f x = x+1.
When we iterate through the whole n and come to the point when id is being called what happens with our variables?
I am very big newbie so could you please explain as simplistically as possible.
Summing a list xs = [x1,x2,...,xn] can be visualized as
x1 + x2 + ... + xn + 0
Note that + 0 at the very end. Its purpose is to handle the case where the list is empty, i.e. xs = [] and n=0. In such case the sum above reduces to 0, which is the correct sum for an empty list.
Also note that when the list is not empty the extra + 0 has no impact ont the sum, so it's harmless. We indeed choose 0 since it is the neutral element for addition: x + 0 = x for all x.
If we want to compute a product, we would write
x1 * x2 * ... * xn * 1
Note that * 1 at the end. Its role is exactly the same as the + 0 seen above. Also note that 1 is the neutral element of multiplication: x * 1 = x for all x.
If we want to compute the composition of a list of functions, we would write
f1 . f2 . ... . fn . id
Note that . id at the end. Its role is exactly the same as the + 0 and * 1 seen above. Also note that id is the neutral element of composition f . id = f for all f.
Hopefully this will help you understand why, every time we compute a fold like
x1 op x2 op ... op xn
where op is any binary operation, we want to end with ... op neutral_element so to handle the empty list case, and still act as a good base case for non-empty lists.
You can inline:
iter 3 f
f . iter 2 f
f . (f . iter 1 f)
f . (f . (f . iter 0 f)
f . (f . (f . id))
-- adding the argument x
iter 3 f x
(f . (f . (f . id))) x
-- using (g . h) x == g (h x)
f ((f . (f . id)) x)
f (f ((f . id) x))
f (f (f (id x)))
f (f (f x))
And in the case of iter':
iter' 3 f
(foldr (.) id . replicate 3) f
foldr (.) id (replicate 3 f)
foldr (.) id [f, f, f]
(.) f (foldr (.) id [f, f]]
(.) f ((.) f (foldr (.) id [f]))
(.) f ((.) f ((.) f (foldr (.) id [])))
(.) f ((.) f ((.) f id))
f . (f . (f . id))

Dot in haskell, tricky example

I know that "haskells dot" question was answered couple times before on stackoverflow but I came across a example that shows me I still don't fully get it. Let's say I have functions
f :: Integer -> Integer
f x = x
g x = \y -> y
Now, as far as I know dot works like function composition -> f (g x) = (f . g) x
. So
(f . g) 4 5
shuld returns 5. Because g takes two arguments and returns second one, and f is simply identity. However it doesn't, Im getting Couldn't match type error. I have a feeling that haskell parses this expresion to something like ((f . g) 4) 5. But I need deeper explanation
As mentioned in the question, we have:
(f . g) x = f (g x)
Hence, in particular
(f . g) 4 = f (g 4) (*)
from which we have
(f . g) 4 5
= -- application associates to the left
((f . g) 4) 5
= -- equation (*) above
(f (g 4)) 5 =
= -- application associates to the left
f (g 4) 5
We can now see that the last argument 5 is being left as the second argument of f, and not passed to g.
It is useful to remember that Haskell functions are curried: technically, there's no such a thing as a function which takes two arguments. A function having type a -> b -> c is actually a unary function returning a unary function, even if we like to think of that as a binary function.
The composition operator works on unary functions as well: f . g composes the unary functions f and g. If f is "binary", it is treated as a unary function returning a function. This makes it take an additional argument, as shown above. If g is "binary", its returned function is passed to f.
So, using the above definitions:
f x = x
g x = \y -> y
we get:
(f . g) 4 5
= -- done above
f (g 4) 5
= -- associativity
(f (g 4)) 5
= -- definition of f
(g 4) 5
= -- definition of g
(\y -> y) 5
= -- beta reduction
5
main = print $(f . g) 4 5
f x = x
g x = \y -> y
Compiles nicely and when run prints 5. I'm using GHC 8.0.1.
Maybe you'd rather provide a complete minimal etc. example?

Point Free problems in Haskell

I am trying to convert the following Haskell code to point free style, to no avail.
bar f g xs = filter f (map g xs )
I'm new to Haskell and any help would be great.
Converting to pointfree style can be done entirely mechanically, though it's hard without being comfortable with the fundamentals of Haskell syntax like left-associative function application and x + y being the same as (+) x y. I will assume you are comfortable with Haskell syntax; if not, I suggest going through the first few chapters of LYAH first.
You need the following combinators, which are in the standard library. I have also given their standard names from combinator calculus.
id :: a -> a -- I
const :: a -> b -> a -- K
(.) :: (b -> c) -> (a -> b) -> (a -> c) -- B
flip :: (a -> b -> c) -> (b -> a -> c) -- C
(<*>) :: (a -> b -> c) -> (a -> b) -> (a -> c) -- S
Work with one parameter at a time. Move parameters on the left to lambdas on the right, e.g.
f x y = Z
becomes
f = \x -> \y -> Z
I like to do this one argument at a time rather than all at once, it just looks cleaner.
Then eliminate the lambda you just created according to the following rules. I will use lowercase letters for literal variables, uppercase letters to denote more complex expressions.
If you have \x -> x, replace with id
If you have \x -> A, where A is any expression in which x does not occur, replace with const A
If you have \x -> A x, where x does not occur in A, replace with A. This is known as "eta contraction".
If you have \x -> A B, then
If x occurs in both A and B, replace with (\x -> A) <*> (\x -> B).
If x occurs in just A, replace with flip (\x -> A) B
If x occurs in just B, replace with A . (\x -> B),
If x does not occur in either A or B, well, there's another rule we should have used already.
And then work inward, eliminating the lambdas that you created. Lets work with this example:
f x y z = foo z (bar x y)
-- Move parameter to lambda:
f x y = \z -> foo z (bar x y)
-- Remember that application is left-associative, so this is the same as
f x y = \z -> (foo z) (bar x y)
-- z appears on the left and not on the right, use flip
f x y = flip (\z -> foo z) (bar x y)
-- Use rule (3)
f x y = flip foo (bar x y)
-- Next parameter
f x = \y -> flip foo (bar x y)
-- Application is left-associative
f x = \y -> (flip foo) (bar x y)
-- y occurs on the right but not the left, use (.)
f x = flip foo . (\y -> bar x y)
-- Use rule 3
f x = flip foo . bar x
-- Next parameter
f = \x -> flip foo . bar x
-- We need to rewrite this operator into normal application style
f = \x -> (.) (flip foo) (bar x)
-- Application is left-associative
f = \x -> ((.) (flip foo)) (bar x)
-- x appears on the right but not the left, use (.)
f = ((.) (flip foo)) . (\x -> bar x)
-- use rule (3)
f = ((.) (flip foo)) . bar
-- Redundant parentheses
f = (.) (flip foo) . bar
There you go, now try it on yours! There is not really any cleverness involved in deciding which rule to use: use any rule that applies and you will make progress.
Both of the existing answers don't really answer your specific question in a way that's elucidating: one is "here are the rules, work it out for yourself" and the other is "here is the answer, no information about how the rules generate it."
The first three steps are really easy and consist in removing a common x from something of the form h x = f (g x) by writing h = f . g. Essentially it's saying "if you can write the thing in the form a $ b $ c $ ... $ y $ z and you want to remove the z, change all the dollars to dots, a . b . c . ... . y:
bar f g xs = filter f (map g xs)
= filter f $ (map g xs)
= filter f $ map g $ xs -- because a $ b $ c == a $ (b $ c).
bar f g = filter f . map g
= (filter f .) (map g)
= (filter f .) $ map $ g
bar f = (filter f .) . map
So this last f is the only tricky part, and it's tricky because the f is not at the "end" of the expression. But looking at it, we see that this is a function section (. map) applied to the rest of the expression:
bar f = (.) (filter f) . map
bar f = (. map) $ (.) $ filter $ f
bar = (. map) . (.) . filter
and that's how you reduce an expression when you don't have complicated things like f x x and the like appearing in it. In general there is a function flip f x y = f y x which "flips arguments"; you can always use that to move the f to the other side. Here we have flip (.) map . (.) . filter if you include the explicit flip call.
I asked lambdabot, a robot who hangs out on various Haskell IRC channels, to automatically work out the point-free equivalent. The command is #pl (pointless).
10:41 <frase> #pl bar f g xs = filter f (map g xs )
10:41 <lambdabot> bar = (. map) . (.) . filter
The point free version of bar is:
bar = (. map) . (.) . filter
This is arguably less comprehensible than the original (non-point-free) code. Use your good judgement when deciding whether to use point-free style on a case-by-case basis.
Finally, if you don't care for IRC there are web-based point-free
converters such as pointfree.io, the pointfree command line program, and other tools.

High order function returning result and modified itself

My goal is to create function, which take argument, compute result and return it in tuple with modified itself.
My first try looked like this:
f x = (x,f') where
f' y = (y+1,f')
cl num func = let (nu,fu) = func num in nu:fu num
My desired result if I call function cl with 0 and f was
[0,1,2,3,4,5,6,7,8,9,10,11,12,13 ... infinity]
Unfortunately, haskell cannot construct infinite type. It is hard for me to devise another way of doing it. Maybe, I'm just looking at problem from the bad side, thats why I posted this question.
EDIT:
This is the state of my functions:
newtype InFun = InFun { innf :: Int -> (Int,InFun) }
efunc x = (x,InFun deep) where
deep y = (y+1, InFun deep)
crli n (InFun f) = let (n',f') = f n in n':crli n f'
main = putStrLn $ show (take 10 (crli 0 (InFun efunc)))
Result is [0,1,1,1,1,1,1,1,1,1]. That's better, But, I want the modification made by deep function recursive.
Probably you are looking for
{-# LANGUAGE RankNTypes #-}
newtype F = F { f :: Int -> (Int, F) }
g y = (y + 1, F g)
then
*Main> fst $ (f $ snd $ g 3) 4
5
or
*Main> map fst $ take 10 $ iterate (\(x, F h) -> h x) (g 0)
[1,2,3,4,5,6,7,8,9,10]
or more complex modification (currying)
h = g False
where g x y = (y', F g')
where y' = if x then y + 1
else 2 * y
g' = if x then g False
else g True
then
*Main> map fst $ take 10 $ iterate (\(x, F h) -> h x) (h 0)
[0,1,2,3,6,7,14,15,30,31]
You can use iterate:
iterate (+1) 0

How to call the same function 'n' times? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Library function to compose a function with itself n times
I need a function to call another function n number of times.
so it would look something like this
f n = g(g(g(g(l))))
where n equals to the number of function g nested.
how should I go about this? thanks!
iterate is a common solution:
> :t iterate
iterate :: (a -> a) -> a -> [a]
So, given a function with a domain the same as its range, a -> a, and an initial input a, produce an infinite list of results in the form:
iterate f a --> [a, f(a), f(f(a)), ...]
And you can access the nth element of the list using !!:
iterate f a !! n
NB iterate f a !! 0 == a.
This is a function that I use often at the ghci prompt. There are a few ways to write it, none of which I am particularly fond of, but they are all reasonably clean:
fpow n f x = iterate f x !! n
fpow n f = foldr (.) id $ replicate n f
fpow n = foldr (.) id . replicate n -- just eta the above
fpow 0 f = id
fpow n f = f . fpow (n-1) f
The middle two appeal to me because my brain has chunked foldr (.) id to mean "compose a list of functions".
I kinda just wish it were in the prelude :-).
f 0 = l
f n = g (f (n-1))
But more functional would be:
f 0 l = l
f n l = g (f (n-1) l)
This could also be done with folds or morfisms, but this is easier to understand.
For example here's using a hylomorphism, but it doesn't make it clearer really:
f g l = hylo l (.) (\n -> (g, n-1)) (==0)
It says some thing like compose (.) g(l) until n==0
Can be done using fold:
applyNTimes :: Int -> (a -> a) -> a -> a
applyNTimes n f val = foldl (\s e -> e s) val [f | x <- [1..n]]

Resources