[Haskell-beginners] Calculations that might fail: with arrays

Christopher Howard christopher.howard at frigidcode.com
Thu Jun 9 02:48:55 CEST 2011


On 06/08/2011 04:14 PM, Elvio Toccalino wrote:
> Mmm... well, by looking at the type of it I can't infer what you'd do
> with the returned value of the wrapped function (the action to be
> mapped):
> should that last 'a' be a mappend'ed result of all others? or is it the
> last 'a'? maybe it's meaningless?
> 
> El mié, 08-06-2011 a las 16:09 -0800, Christopher Howard escribió:
>> I was wondering if there was a stock function or package in Haskell that
>> allows you to map over a list, but short-circuits the mapping if any of
>> the calculations fail. Say, something like this:
>>
>> -- Don't know if this is a valid signature! :)
>> mapThatCanFail :: (b -> Either a b) -> [b] -> Either a [b]
>>
>> The idea being that, if any calculations fail, the function doesn't
>> bother mapping the rest of the list, but just returns a Left value
>> (error). Otherwise, it returns a Right value containing the new list.
>>
>> I suppose I could try to implement that myself, but it seems like the
>> sort of thing that someone would have thought of already.
>>
> 
> 

Maybe a (silly) example would help. Say I had a function...

divideFive a = if a == 0
             then Left "can't divide by zero, dipwad!"
             else Right (5 / a)

I could do this...

map divideFive [3,2,0,5]

which returns...

[Right 1.6666666666666667,Right 2.5,Left "can't divide by zero,
dipwad!",Right 1.0]

Let say all my results our worthless if any of the results are
worthless. I can check the above array for Left values to find out if
that is the case. But it's kind of lame because I already mapped my
calculation over the entire list (and plus now must do a search now for
Left values) even though I know that by the third element the remaining
calculations are worthless. (Which would be significant if, say, my list
was 1,000,000 elements long.)

I'm looking for something like this...

specialMap divideFive [3,2,0,5]

returns...

Left "can't divide by zero, dipwad!"

but...

specialMap divideFive [3,2,1,5]

returns...

Right [1.6666666666666667,2.5,5.0,1.0]

-- 
frigidcode.com
theologia.indicium.us



More information about the Beginners mailing list