[Haskell-cafe] Getting an attribute of an object
Jules Bean
jules at jellybean.co.uk
Thu Feb 10 16:00:33 EST 2005
On 10 Feb 2005, at 20:17, Dmitri Pissarenko wrote:
> Hello!
>
> I have a list of instances of the ClassifiedImage class, which is
> defined as
> follows.
>
> data ClassifiedImage = ClassifiedImage {imageFileName :: String,
> subjectID ::
> String}
> deriving Show
>
> Attribute imageFileName contains a file name of a certain image. I want
> to "transform" the list [ClassifiedImage] into a list
> [(ClassifiedImage,
> Image)], where Image is content of the file with name imageFileName.
>
> That is, I want to have a routine, which iterates through the list of
> ClassifiedImages, reads each file (with filename contained in the
> attribute
> ClassifiedImage.imageFileName) and stores its content in a variable.
>
> I have already a function, which reads the content of a file.
>
> My idea is to use map for this task:
>
> readClassifiedImages :: [ClassifiedImage] -> [(ClassifiedImage, Image)]
> readClassifiedImages classifiedImages = do
> return map readerFunc classifiedImages
>
> readerFunc denotes some function, which takes the attribute
> imageFileName of a
> ClassifiedImage instance.
>
> I suppose that this readerFunc looks like shown below.
>
> readerFunc :: ClassifiedImage -> (ClassifiedImage, Image)
> readerFunc classifiedImage = (classifiedImage, fileContent)
> where fileName = classifiedImageFileName classifiedImage
> fileContent = readImage fileName
>
> classifiedImageFileName :: ClassifiedImage -> String
>
> In order for this function to work, I need to define
> classifiedImageFileName,
> which "returns" the imageFileName attribute of an instance of
> ClassifiedImage
> class.
This is called a selector function. Haskell defines one automatically
with the same name as the field. imageFileName is a function
ClassifiedImage -> String.
(ClassifiedImage is not a class, it's a datatype, by the way)
>
> How can I define this function?
>
> Can I use map for readImage function, which is in the IO domain? If
> not, what
> tutorial can help me?
>
If you're happy to replace Image with IO image, then that will be fine.
Jules
More information about the Haskell-Cafe
mailing list