Reputation: 44
I am new to Haskell and I have the following problem. I have to create a list of numbers [f1, f2, f3...] where fi x = x ^ i
. Then I have to create a function that applies the fi
to a list of numbers. For example if I have a list lis = [4,5,6,7..]
the output would be [4^1, 5^2,6^3, 7^4...]
. This is what I have written so far :
powers x= [x^y |y<-[1,2,3,4]]
list = [1,2,3,4]
match :: (x -> xs) -> [x] -> [xs]
match f [] = []
match f (x:xs) = (f x) : ( match f xs )
So if I put the list = [1,2,3] the output is [1,1,1,1][2,4,8,16],[3,9,27,81] instead of [1,4,27]
Can you please tell me what is wrong and point me to the right direction?
Upvotes: 2
Views: 2508
Reputation: 3217
The first issue is that powers
is of type Int -> [Int]
. What you really want, I think, is something of type [Int -> Int]
-- a list of Int -> Int
functions instead of a function that takes an Int
and returns a list of Int
. If you define powers
like so:
powers = [(^y) | y <- [1..4]]
you can use zipWith
to apply each power to its corresponding element in the list, like so:
zipWith ($) powers [1,2,3] -- returns [1,4,27]
The ($)
applies its left (first) argument to its right (second) argument.
Note that using powers
as defined here will limit the length of the returned list to 4. If you want to be able to use arbitrary length lists, you want to make powers
an infinite list, like so:
powers = [(^y) | y <- [1..]]
Of course, as dave4420 points out, a simpler technique is to simply use
zipWith (^) [1,2,3] [1..] -- returns [1,4,27]
Upvotes: 6
Reputation: 9662
You are currently creating a list for every input value. What you need to do is recursively compute the appropriate power for each input value, like this:
match f [] = []
match f (x:xs) y = (f x y) : (match f xs y+1)
Then, you can call this as match pow [1, 2, 3] 1
.
This is equivalent to using zipWith and providing the desired function (pow
), your input list ([1, 2, 3]
) and the exponent list (a lazy one to infinity list) as arguments.
Upvotes: 1