Reputation: 27
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).
Upvotes: 0
Views: 1413
Reputation: 144206
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 e.g. MyType Int String Bool
then you can do:
let mapped = map (\i -> MyType i "test" True) MyList
Upvotes: 3
Reputation: 7476
When writing data MyType = MyType Int
you are declaring a type MyType with a single *constructor*
MyTypewhich takes an
Intand 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.
Upvotes: 0