[英]Haskell mapping function to list
I am new to Haskell and I have the following problem. 我是Haskell的新手,我有以下问题。 I have to create a list of numbers [f1, f2, f3...] where
fi x = x ^ i
. 我必须创建一个数字列表[f1,f2,f3 ...],其中
fi x = x ^ i
。 Then I have to create a function that applies the fi
to a list of numbers. 然后我必须创建一个将
fi
应用于数字列表的函数。 For example if I have a list lis = [4,5,6,7..]
the output would be [4^1, 5^2,6^3, 7^4...]
. 例如,如果我有一个列表
lis = [4,5,6,7..]
则输出将为[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] 所以,如果我把list = [1,2,3]输出为[1,1,1,1] [2,4,8,16],[3,9,27,81]而不是[1, 4,27]
Can you please tell me what is wrong and point me to the right direction? 你能告诉我出了什么问题并指出了正确的方向吗?
The first issue is that powers
is of type Int -> [Int]
. 第一个问题是
powers
类型为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
. 我认为你真正想要的是
[Int -> Int]
- Int -> Int
函数列表,而不是一个接受Int
并返回Int
列表的函数。 If you define powers
like so: 如果你定义这样的
powers
:
powers = [(^y) | y <- [1..4]]
you can use zipWith
to apply each power to its corresponding element in the list, like so: 您可以使用
zipWith
将每个电源应用于列表中的相应元素,如下所示:
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
会将返回列表的长度限制为4.如果您希望能够使用任意长度列表,则需要将powers
为无限列表,如下所示:
powers = [(^y) | y <- [1..]]
Of course, as dave4420 points out, a simpler technique is to simply use 当然,正如dave4420所指出的,一种更简单的技术就是简单地使用
zipWith (^) [1,2,3] [1..] -- returns [1,4,27]
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
. 然后,您可以将其称为
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. 这相当于使用zipWith并提供所需的函数(
pow
),输入列表( [1, 2, 3]
)和指数列表(懒惰的一个到无穷大列表)作为参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.