Вопрос

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 e.g. 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*MyTypewhich takes anIntand create an object of typeMyType`.

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top