[Haskell-beginners] How to process a list that contains "undefined" values?

Daniel Fischer daniel.is.fischer at googlemail.com
Sat Jul 2 16:32:37 CEST 2011


On Saturday 02 July 2011, 16:09:05, Costello, Roger L. wrote:
> Hi Folks,
> 
> How would you find the maximum value in this list:
> 
>      [undefined, 10, undefined, 20]

Not. There is no proper maximum in the presence of undefined.
If you absolutely have to do something like that, you would have to use 
Control.Exception.catch to catch the undefined values and ignore 
them/remove them from the list. But if your undefined values are not so 
nice as Prelude.undefined but actually nonterminating computations, 
calculating the maximum won't terminate either.

> 
> Is it bad practice to create lists that contain undefined values?

That depends on how they will be further processed. Sometimes it's 
perfectly fine to have undefined values in a list, sometimes not.

> 
> If yes, what is a better way to express in a list a "no value
> present/available" value?
> 
> For example would it be better to express the above list using Maybe:
> 
>     [Nothing, Just 10, Nothing, Just 20]

Yes. If possible, indicating the absence of a value via Maybe is the right 
thing to do. Or something including a message why there is no value in a 
particular place, like Either err val.

> 
> Or perhaps something else?
> 
> What do you recommend?

[Maybe Integer], [Either Message Integer], whatever is more appropriate; 
then you can use functions like catMaybes or partitionEithers, rights, 
lefts, ... to cleanly process the list.





More information about the Beginners mailing list