This question already has answers here:
How to call the same function 'n' times? [duplicate]
(4 answers)
Library function to compose a function with itself n times
(10 answers)
Closed 8 years ago.
Learn You a Haskell For Great Good (section "Higher Order Functions", subsection "Some higher-orderism is in order") describes an example function applyTwice that calls a function on an argument twice:
applyTwice :: (a -> a) -> a -> a
applyTwice f x = f (f x)
But i need a function that applies some function over some argument an arbitrary amount of times. For example applyN 3 f x would be equivalent to f $ f $ f x. How would i write a function of repeated application in Haskell? Please post any possible solutions, using recursion, higher-order functions or anything else.
I always did something like iterate f x !! n.
You will have to do a recursive function. The obvious case will be be when you apply the function 0 time, it will be like you don't modify the input. The recursive will come from the fact that applyN n f x == f (applyN (n -1) f x or because composition of function is associative applyN n f x == apply (n - 1) f (f x). The second option lead to better performance because it will be tail recursive
applyN :: Int n => n -> (a -> a) -> a -> a
applyN 0 _ x = x
applyN n f x = applyN (n - 1) f (f x)
applyN = (foldr (.) id.) . replicate
-->>
applyN 0 f = id
applyN 1 f = f
applyN 2 f = (f.f)
-- ...
Or just use iterate, as was already said before. The only real difference is that using iterate you will get an exception if you use a negative n, whereas in this solution you'd get id. If that's a case that can plausibly happen for your use case, you should consider which is the behavior you like better.
Related
Can someone explain to me whats going on in this function?
applyTwice :: (a -> a) -> a -> a
applyTwice f x = f (f x)
I do understand what curried functions are, this could be re-written like this:
applyTwice :: ((a -> a) -> (a -> (a)))
applyTwice f x = f (f x)
However I dont fully understand the (+3) operator and how it works. Maybe it's something really stupid but I can't figure it out.
Can someone explain step by step how the function works? Thanks =)
applyTwice :: ((a -> a) -> (a -> (a)))
applyTwice f x = f (f x)
Haskell has "operator slicing": if you omit one or both of the arguments to an operator, Haskell automatically turns it into a function for you.
Specifically, (+3) is missing the first argument (Haskell has no unary +). So, Haskell makes that expression into a function that takes the missing argument, and returns the input value plus 3:
-- all the following functions are the same
f1 x = x + 3
f2 = (+3)
f3 = \ x -> x + 3
Similarly, if you omit both arguments, Haskell turns it into a function with two (curried) arguments:
-- all the following functions are the same
g1 x y = x + y
g2 = (+)
g3 = \ x y -> x + y
From comments: note that Haskell does have unary -. So, (-n) is not an operator slice, it just evaluates the negative (same as negate n).
If you want to slice binary - the way you do +, you can use (subtract n) instead:
-- all the following functions are the same
h1 x = x - 3
h2 = subtract 3
h3 = \ x -> x - 3
I want to define min function to get minimum number on a list using Foldr function
min xs = foldr (\ x y -> if x<y then x else y) xs
Although I understand the logic of Foldr for simple functions like below
sum = foldr (+) 0
I get confused how to do it for function like min
The type signature of foldr is:
foldr :: (a -> b -> b) -> b -> [a] -> b
In particular, foldr takes three arguments, so your definition for min is missing
one value:
min xs = foldr (\ x y -> if x<y then x else y) ??? xs
In the case of sum = foldr (+) 0, the argument 0 is the value of sum on the empty list.
Likewise, the missing argument ??? should be the value for min on the empty list. But does min [] even make any sense?
The way to resolve this is to realize that min should only be called on non-empty lists and write:
min [] = error "min called on an empty list"
min (a:as) = foldr (\x y -> if x < y then x else y) ??? as
To determine what ??? should be, just ask yourself: what should min (a:as) be when as = []?
min is best viewed as a left fold rather than a right fold. The trouble with the right fold approach is that no comparisons happen until the list has already been entirely traversed. If the list is generated lazily, this will lead to a lot of excess memory use. Even if it's not, it will likely lead to poor use of cache and general slowness. The rest of this answer is much less practical.
As http://www.haskell.org/haskellwiki/Foldl_as_foldr shows, it's actually possible to write foldl in terms of foldr:
foldl :: (a -> b -> a) -> a -> [b] -> a
foldl f a bs =
foldr (\b g x -> g (f x b)) id bs a
This is not going to be such a great implementation in general, but recent developments in program transformation have actually made it work okay, apparently, although maybe not in an actual released compiler!
Then
foldl1 f (a:as) = foldl f a as
= foldr (\b g x -> g (f x b)) id as a
Now write
min2 x y
| x <= y = x
| otherwise = y
Then
min = foldl1 min2
So we can write
min (a:as) = foldr (\b g x -> g (min2 x b)) id as a
and (on a bleeding edge research compiler) this is probably the best way to use foldr to implement min.
I am trying to understand "Löb and möb: strange loops in Haskell", but right now the meaning is sleaping away from me, I just don't see why it could be useful. Just to recall function loeb is defined as
loeb :: Functor f => f (f a -> a) -> f a
loeb x = go where go = fmap ($ go) x
or equivalently:
loeb x = go
where go = fmap (\z -> z go) x
In the article there is an example with [] functor and spreadsheets implementation, but it is bit foreign for me just as spreadsheets themselves (never used them).
While I'm understanding that spreadsheet thing, I think it would help a lot for me and others to have more examples, despite lists. Is there any application for loeb for Maybe or other functors?
The primary source (I think) for loeb is Dan Piponi's blog, A Neighborhood of Infinity. There he explains the whole concept in greater detail. I'll replicate a little bit of that as an answer and add some examples.
loeb implements a strange kind of lazy recursion
loeb :: Functor a => a (a x -> x) -> a x
loeb x = fmap (\a -> a (loeb x)) x
Let's imagine we have a type a, where Functor a, and an a-algebra (a function of type a x -> x). You might think of this as a way of computing a value from a structure of values. For instance, here are a few []-algebras:
length :: [Int] -> Int
(!! 3) :: [a] -> a
const 3 :: Num a => [a] -> a
\l -> l !! 2 + l !! 3 :: Num a => [a] -> a
We can see that these a-algebras can use both values stored in the Functor and the structure of the Functor itself.
Another way to think of d :: a x -> x is as a value of x which requires some context–a whole Functorized value a x–in order to be computed. Perhaps this interpretation is more clearly written as Reader (a x) x, emphasizing that this is just a value of x which is delayed, awaiting the a x context to be produced.
type Delay q x = q -> x
Using these ideas we can describe loeb as follows. We're given a f-structure containing some Delayed values, where f is a Functor
Functor f, f (Delay q x)
Naturally, if we were given a q then we could convert this into a not delayed form. In fact, there's only one (non-cheating) function that does this polymorphically:
force :: Functor f => f (Delay q x) -> q -> f x
force f q = fmap ($ q) f
What loeb does is handle the extra tricky case where q is actually force f q, the very result of this function. If you're familiar with fix, this is exactly how we can produce this result.
loeb :: Functor a => a (Delay (a x) x) -> a x
loeb f = fix (force f)
So to make an example, we simply must build a structure containing Delayed values. One natural example of this is to use the list examples from before
> loeb [ length :: [Int] -> Int
, const 3 :: [Int] -> Int
, const 5 :: [Int] -> Int
, (!! 2) :: [Int] -> Int
, (\l -> l !! 2 + l !! 3) :: [Int] -> Int
]
[5, 3, 5, 5, 10]
Here we can see that the list is full of values delayed waiting on the result of evaluating the list. This computation can proceed exactly because there are no loops in data dependency, so the whole thing can just be determined lazily. For instance, const 3 and const 5 are both immediately available as values. length requires that we know the length of the list but none of the values contained so it also proceeds immediately on our fixed-length list. The interesting ones are the values delayed waiting on other values from inside our result list, but since (!! 2) only ends up depending on the third value of the result list, which is determined by const 5 and thus can be immediately available, the computation moves forward. The same idea happens with (\l -> l !! 2 + l !! 3).
So there you have it: loeb completes this strange kind of delayed value recursion. We can use it on any kind of Functor, though. All we need to do is to think of some useful Delayed values.
Chris Kuklewicz's comment notes that there's not a lot you could do interestingly with Maybe as your functor. That's because all of the delayed values over Maybe take the form
maybe (default :: a) (f :: a -> a) :: Maybe a -> a
and all of the interesting values of Maybe (Delay (Maybe a) a) ought to be Just (maybe default f) since loeb Nothing = Nothing. So at the end of the day, the default value never even gets used---we always just have that
loeb (Just (maybe default f)) == fix f
so we may as well write that directly.
You can use it for dynamic programming. The example that comes to mind is the Smith-Waterman algorithm.
import Data.Array
import Data.List
import Control.Monad
data Base = T | C | A | G deriving (Eq,Show)
data Diff = Sub Base Base | Id Base | Del Base | Ins Base deriving (Eq,Show)
loeb x = let go = fmap ($ go) x in go
s a b = if a == b then 1 else 0
smithWaterman a' b' = let
[al,bl] = map length [a',b']
[a,b] = zipWith (\l s -> array (1,s) $ zip [1..] l) [a',b'] [al,bl]
h = loeb $ array ((0,0),(al,bl)) $
[((x,0),const 0) | x <- [0 .. al]] ++
[((0,y),const 0) | y <- [1 .. bl]] ++
[((x,y),\h' -> maximum [
0,
(h' ! (x - 1,y - 1)) + s (a ! x) (b ! y),
(h' ! (x - 1, y)) + 1,
(h' ! (x, y - 1)) + 1
]
) | x <- [1 .. al], y <- [1 .. bl]]
ml l (0,0) = l
ml l (x,0) = ml (Del (a ! x): l) (x - 1, 0)
ml l (0,y) = ml (Ins (b ! y): l) (0, y - 1)
ml l (x,y) = let
(p,e) = maximumBy ((`ap` snd) . (. fst) . (const .) . (. (h !)) . compare . (h !) . fst) [
((x - 1,y),Del (a ! x)),
((y, x - 1),Ins (b ! y)),
((y - 1, x - 1),if a ! x == b ! y then Id (a ! x) else Sub (a ! x) (b ! y))
]
in ml (e : l) p
in ml [] (al,bl)
Here is a live example where it is used for: Map String Float
http://tryplayg.herokuapp.com/try/spreadsheet.hs/edit
with loop detection and loop resolution.
This program calculates speed, time and space. Each one depends on the other two. Each cell has two values: his current entered value and the expression as a function of the other cell values/expressions. circularity is permitted.
The Cell recalculation code uses the famous loeb expression by Dan Piponi in the 2006. Until now by my knowledge there haven't been any materialization of this formula on a real working spreadsheet. this one is close to it. Since loeb enters in a infinite loop when circular expressions are used, the program counts the loops and reduces complexity by progressively substituting formulas by cell values until the expression has no loops
This program is configured for immediate recalculation on cell change, but that can be adapted to allow the modification of more than one cell before recalculation by triggering it by means of a button.
This is blog pos:
http://haskell-web.blogspot.com.es/2014/09/spreadsheet-like-program-in-browser.html
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]]
I really wish that Google was better at searching for syntax:
decades :: (RealFrac a) => a -> a -> [a] -> Array Int Int
decades a b = hist (0,9) . map decade
where decade x = floor ((x - a) * s)
s = 10 / (b - a)
f(g(x))
is
in mathematics : f ∘ g (x)
in haskell : ( f . g ) (x)
It means function composition.
See this question.
Note also the f.g.h x is not equivalent to (f.g.h) x, because it is interpreted as f.g.(h x) which won't typecheck unless (h x) returns a function.
This is where the $ operator can come in handy: f.g.h $ x turns x from being a parameter to h to being a parameter to the whole expression. And so it becomes equivalent to f(g(h x)) and the pipe works again.
. is a higher order function for function composition.
Prelude> :type (.)
(.) :: (b -> c) -> (a -> b) -> a -> c
Prelude> (*2) . (+1) $ 1
4
Prelude> ((*2) . (+1)) 1
4
"The period is a function composition operator. In general terms, where f and g are functions, (f . g) x means the same as f (g x). In other words, the period is used to take the result from the function on the right, feed it as a parameter to the function on the left, and return a new function that represents this computation."
It is a function composition: link
Function composition (the page is pretty long, use search)