0

I'd like to do know the simplest method for adjusting a single stored value whilst hanging on to the pre existing other value. Can I directly access the value of Size, whilst carrying through the pre-existing value of Color?

data Example = Color Size
  deriving (Show)

data Color = C Red Green Blue
  deriving (Show)

data Size = S Small Medium Large
  deriving (Show)

useExample :: Example -> String -> Example
useExample e s = 
  case s of
    "S" -> e.Color Small
    "M" -> e.Color Medium
    "L" -> e.Color Large

Say I have a type with lots of fields, and a value of this type. Is it possible to create another value of this type with all but one field the same, without resorting to writing out all the fields.

This becomes critical when there are many scenarios to consider, the project I'm working on has many more than there are in this example.

Ira Skye
  • 1
  • 1
  • It is not really clear to me what you are looking for, what do you mean with "*Can I directly access the value of Size, whilst carrying through the pre-existing value of Color?*". – Willem Van Onsem Apr 09 '18 at 12:38
  • 1
    `Size` is not an sum type consisting of the three nullary constructors `Small`, `Medium`, and `Large`; it's a type with a single constructor that expects arguments of type `Medium` and `Large`. – chepner Apr 09 '18 at 12:44
  • 1
    I'm not entirely sure what you intend with `e.Color Small`. Haskell doesn't have attributes, and `Color ` isn't a field or component of a value of type `Example`, it's just the constructor. – chepner Apr 09 '18 at 12:45
  • Indeed, probably the OP wanted to write `data Color = Red | Green | Blue`, etc. – Willem Van Onsem Apr 09 '18 at 12:45
  • useExample takes a Example and a String and based on the value of the string it returns Example using the original colour and the matched Size. What I know know how to do is keep the Color to be reused with the matched Size. Does that make sense? – Ira Skye Apr 09 '18 at 12:45
  • See also [this question](https://stackoverflow.com/q/5767129/791604) for a more modern discussion of lens library offerings. – Daniel Wagner Apr 09 '18 at 12:46
  • I don't mean "data Color = Red | Green | Blue". I need to access directly. – Ira Skye Apr 09 '18 at 12:47
  • Say you have a type with lots of fields, and a value of this type. He wants to know if it's easy to create another value of this type with all but one field the same, without resorting to writing out all the fields. – Daniel McLaury Apr 09 '18 at 12:49

0 Answers0