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. 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:
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).
The MyType
constructor is a function Int -> MyType
so you can just use
let mapped = map MyType MyList
If you have a more complicated type eg MyType Int String Bool
then you can do:
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`.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.