2

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?

3 Answers 3

6

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]
Sign up to request clarification or add additional context in comments.

1 Comment

Heh -- that's what I get for imitating the OP's design
3

Your match is the standard function map by another name. You need to use zipWith instead (which you can think of as mapping over two lists side-by-side).

Is this homework?

1 Comment

no it's not homework. i was searching for excercises in haskell and i found it and i thought i could give it a try since i am trying to learn haskell. i will try zipWith thank you .
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.