When I put the following lambda expression in ghci I get 1:
ghci> (\x -> x+1) 0
1
But when I use that function with iterate I get
ghci> take 10 (iterate (\x -> x+1) 0)
[0,1,2,3,4,5,6,7,8,9]
I expected to get a list equal to [1..10]. Why not?
The first result of iterate is the original input without the function applied, i.e. the function is called 0 times. That's why the result is one off from what you expect.
More specifically, iterate is implemented lie this:
iterate f v = v : iterate f (f v)
Just remember that the start value you give to iterate will appear first in thelist - that's it.
Stop...Hoogle time!
http://haskell.org/hoogle/?hoogle=iterate
click iterate
http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:iterate
iterate f x returns an infinite list of repeated applications of f to x:
iterate f x == [x, f x, f (f x), ...]
There you go. It works that way because that's how it says it works. I'm not trying to be flippant, just hoping to illustrate the usefulness of Hoogle and the docs. (Sounds like a good name for a Haskell band: "Hoogle and the Docs")
Related
I'm trying to learn Haskell by solving exercises and looking at others solutions when i'm stuck. Been having trouble understanding as functions get more complex.
-- Ex 5: given a list of lists, return the longest list. If there
-- are multiple lists of the same length, return the list that has
-- the smallest _first element_.
--
-- (If multiple lists have the same length and same first element,
-- you can return any one of them.)
--
-- Give the longest function a suitable type.
--
-- Examples:
-- longest [[1,2,3],[4,5],[6]] ==> [1,2,3]
-- longest ["bcd","def","ab"] ==> "bcd"
longest :: (Foldable t, Ord a) => t [a] -> [a]
longest xs = foldl1 comp xs
where
comp acc x | length acc > length x = acc
| length acc == length x = if head acc < head x then acc else x
| otherwise = x
So foldl1 works as follows - input: foldl1 (+) [1,2,3,4] output: 10. As I understand it, it takes a function applies it to a list and "folds" it. The thing I don't understand is that comp acc x compares two lists and outputs the larger length list.
The thing I don't understand is with longest xs = foldl1 comp xs. How are two lists provided to comp to compare and what is foldl1 "folding" and what is the start accumulator?
Here is another shorter example of another fold that I thought I understood.
foldl - input: foldl (\x y -> x + y) 0 [1,2,3] output: 6
It starts at 0 and adds each element from left one by one. How does foldl exactly apply the two variables in the anonymous function. For instance if the anonymous function was (\x y z-> x + y + z) it would fail which I don't yet understand why.
I think your current notion of what foldl1/foldl does is not quite accurate. As others already explained foldl1 f (x:xs) == foldl f x xs so the first value in the list is taken as an accumulator.
You say that foldl1 (+) list takes each value of the list "one by one" and computes the sum. I think this notion is misleaing: Actually you do always take two values, add them and get an intermediate result. And you repeat that over and over again with one of the values being the intermediate result of the last. I really like following illustration:
Source
If you start to think about these intermediate values, it will make more sense that you always get the largets one.
I think it is easiest to understand if you look at a symbolic example:
foldl k z [a, b, c] = k (k (k z a) b) c
foldl1 k [a, b, c] = k (k a b) c
As you can see foldl1 just starts with the first two arguments and then adds on the rest one by one using k to combine it with the accumulator.
And foldl starts by applying k to the initial accumulator z and the first element a and then adds on the rest one by one.
The k function only ever gets two arguments, so you cannot use a function with three arguments for that.
I'm sorry if the title was misleading but I'm not even sure what is my question. I have the following exercise:
We call x a fix point of a function f if f x==x (i.e. f maps x to itself). Write a function fixpoint which accepts a function f :: Integer -> Integer and returns the smallest non-negative integer x which is a fix
point of f.
So far all I could think off was:
fixpoint :: (a -> a) -> a
fixpoint f = min [f x | x<-[0..n], f x == x ]
but it is obviously flawed as the n is out of nowhere.
I've tried other things too but they were obvious mistakes.
What is a possible solution to this exercise? I'm new to Haskell and I don't even know how to think about that problem.
There are other ways to solve it, but expanding on your idea, you can use [0..] to create an infinite list, so you don't need the n. Then you can't take the min of an infinite list, because it will never complete, but since your list counts up, the smallest one will be the first one, so you can use head:
fixpoint f = head [f x | x <- [0..], f x == x]
In Haskell, I'm trying to solve a problem where I need to have a function that receives a list of integers and returns the biggest product of two adjacent numbers.
Example: f [5,6,1,3,9] would return 30, that is the product of 5 and 6
The function type would be something like this:
f :: [Int] -> Int
I thought to solve that using recursion to iterate the list getting the 2 head elements with a pattern like this: (x1:x2:xs)
The problem is that I don't know how to keep the product value to compare if the current product is bigger than the last product.
Any ideas?
Since Haskell lists are lazy, you can solve this problem using a list-based approach instead of explicitly holding onto a maximum without losing efficiency. Starting with the original list:
> let f x = x
> f [5,6,1,3,9]
[5,6,1,3,9]
get a list of pairs by zipping the entire list with a left-shifted list:
> let f x = zip x (tail x)
> f [5,6,1,3,9]
[(5,6),(6,1),(1,3),(3,9)]
use the related function zipWith to get products instead of pairs:
> let f x = zipWith (*) x (tail x)
> f [5,6,1,3,9]
[30,6,3,27]
and get the maximum from that list:
> let f x = maximum (zipWith (*) x (tail x))
> f [5,6,1,3,9]
30
I'm having the above function, but when I call it, it gets stuck, the Data.List.iterate evaluates without stopping.
rp:: RandomGen g => g -> ([Int], g)
rp g = (map (\x -> (last (fst x))) lst , snd (next g))
where
lst = (Data.List.iterate id ([1], g_second))
(g_first, g_second) = (split g)
Why does that happend?
Thank you!
While I'm not exactly sure what you're trying to achieve with your function, the reason it doesn't stop is because you're mapping over an infinite list and giving it no reason to stop.
The infinite list originates in your use of iterate:
lst = (Data.List.iterate id ([1], g_second))
What you've done there is create an infinite list which contains an infinite number of the tuple value ([1], g_second). That seems like a logic error - that list of tuple has no variation; every element is the same, to infinity. To be clear, this list you are building looks like this:
[([1], g_second), ([1], g_second), ([1], g_second), ([1], g_second)...]
g_second is unchanging and never gets a reason to evaluate, so it is, in essence, discarded.
If you were to use something like take or takeWhile, you could force that infinite list to stop and return a known number of elements. However, by using map in this statement:
map (\x -> (last (fst x))) lst
All you are doing is pulling the value 1 out of the tuple and repeating it forever.
And since you discard g_second and never use g_first, your function is equivalent to the following:
rp :: RandomGen g => g -> ([Int], g)
rp g = (repeat 1 , snd (next g))
Assuming you want to generate an infinite list of random-numbers based on a RandomGen g then you can use Data.List.unfold as it fit's next nicely:
> import System.Random
> import Data.List
> let rnds g = unfoldr (Just . next) g
> let rnds' = rnds (mkStdGen 0)
> take 3 rnds'
[2147482884,2092764894,1390461064]
BTW: yes the final g is missing - but to get this you would have to generate the infinite list first ... which seems unlikely (plus it would not fit unfoldr as nicely ;))
I'm trying to implement a function using list comprehensions that copies an element an amount of times as specified. I'm really stuck on this but I'm trying to
for example
copy 2 'a' = aa
This is what I have so far:
copy2 :: Int->a->[a]
copy2 x y = func1 y [b|b<-[1..x]]
where func1 is somehow mapping y to every element of x
It's not a lot but I'm really clueless on this one sorry guys.
Even though an answer has been accepted, I want to point out that you said something profoundly important in your very question, which could have led you to an answer.
You said:
copy2 :: Int->a->[a]
copy2 x y = func1 y [b|b<-[1..x]]
where func1 is somehow mapping y to every element of x
If we clean up the phrasing a bit -- I am sure it's what you meant -- we actually want something that maps every element of the list produced by the comprehension to the constant value y.
Well, making a function that produces a value y for a single x is simple:
const y x = y
In fact, the function is useful enough that it exists in the Prelude already!
Now we just need to map over every element of the list.
copy2 x y = map (const y) [b | b <- [1..x]]
or a bit simplified, to really show how close we are to your original description, (even though I know you needed the list comprehension)
copy2 x y = map (\x -> y) [1..x]
"map x to y for every x."
So you see, you had it all along.
copy2 qty item = [item|_<-[1..qty]]