[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [sc-dev] Empty string .asInteger returns 0



Em 29-12-2013 12:31, James Harkins escreveu:
> On Dec 29, 2013 7:45 PM, "Eirik Arthur Blekesaune"
> <eirik.blekesaune@xxxxxxxxx <mailto:eirik.blekesaune@xxxxxxxxx>> wrote:
>>
>> Why does "".asInteger return 0? Wouldn't it be more correct to return nil?
>> Same goes for "".asInt btw?
> 
> I think, if you're converting a string to an integer, you should get an
> integer back. Nil isn't an integer, so...
> 
> The precedent is the atoi() function in C:
> 
> http://www.cplusplus.com/reference/cstdlib/atoi/
> 
> "If the first sequence of non-whitespace characters in str is not a
> valid integral number, or if no such sequence exists because either str
> is empty or it contains only whitespace characters, no conversion is
> performed and zero is returned."
> 
> hjh
> 

I don't find that reasoning convicing at all. Some strings can't be
parsed into integers so the function must have a mechanism for failing,
it can throw an error or return a value which represents a failure (nil,
Nothing, Failure("failure string") etc). How do you even distinguish a
proper match "0".asInteger from a failure "".asInteger ? I don't think
most parsers would give a parse result when the parse has failed... In
haskell's basic parser you get to choose how do you want the function to
fail:

Prelude> (read "asdasd")::Int
*** Exception: Prelude.read: no parse

Prelude Text.Read> (readMaybe "asdasd")::Maybe Int
Nothing

Prelude Text.Read> (readEither "asdasd")::Either String Int
Left "Prelude.read: no parse"

best,
-- 
Miguel Negrão
http://www.friendlyvirus.org/miguelnegrao

Attachment: signature.asc
Description: OpenPGP digital signature