[英]Mapping a type to a list in Haskell
I want to map new instances of a type to the content of a list. 我想将类型的新实例映射到列表的内容。 For example: 例如:
MyList = [1..10]
data MyType = MyType Int
map (MyType (\x -> x)) MyList
I want to get something like [MyType, MyType ...] in which every MyType Int value come from the list. 我想得到类似[MyType,MyType ...]的东西,其中每个MyType Int值都来自列表。 This doesn't work, how can I achieve this? 这行不通,我该如何实现? Or there are better way? 还是有更好的方法?
Thank you! 谢谢!
edit: I forgot that MyType is more complex, for example: 编辑:我忘记了MyType更复杂,例如:
data MyType = MyType Int String Bool
so, how can I map just the ints in the list to the Int part of MyType keeping the other values fixed like MyType ... "test" True (that's why I thought of lambda). 因此,如何将列表中的整数映射到MyType的Int部分,同时保持其他值固定不变,例如MyType ...“ test” True(这就是为什么我想到了lambda的原因)。
The MyType
constructor is a function Int -> MyType
so you can just use MyType
构造函数是MyType
Int -> MyType
函数,因此您可以使用
let mapped = map MyType MyList
If you have a more complicated type eg MyType Int String Bool
then you can do: 如果您有更复杂的类型,例如MyType Int String Bool
则可以执行以下操作:
let mapped = map (\i -> MyType i "test" True) MyList
When writing data MyType = MyType Int
you are declaring a type MyType with a single *constructor*
MyType which takes an
Int and create an object of type
MyType`. 当写入data MyType = MyType Int
您将声明一个MyType with a single *constructor*
MyType的MyType 类型 MyType with a single *constructor*
该类型 which takes an
Int and create an object of type
MyType and create an object of type
。
The sometimes confusing part is that the convention is to use the same name for the type and the constructor when there is only one - like you did. 有时令人困惑的是,约定是在只有一个类型和构造函数时使用相同的名称-就像您所做的那样。 You could perfectly write: 您可以完美地写:
data MyType = MyConstructor Int
In this case, as @Lee pointed out, MyConstructor
is a function of type Int -> MyType
so you can just pass it as first argument of the map
function. 在这种情况下,正如@Lee所指出的, MyConstructor
是Int- Int -> MyType
类型的函数,因此您可以将其作为map
函数的第一个参数传递。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.