Zulip Chat Archive

Stream: lean4

Topic: toNat?


Marcus Rossel (Jun 25 2022 at 16:30):

Calling String.toNat?on the empty string yields some 0. Is this intended?
(Also, "".isNat evaluates to true).

Henrik Böving (Jun 25 2022 at 16:32):

I'm assuming you mean toNat?

Marcus Rossel (Jun 25 2022 at 16:32):

Henrik Böving said:

I'm assuming you mean toNat?

Yes, sorry - I've updated the title and question.

Henrik Böving (Jun 25 2022 at 16:34):

Looking at the implementation of both it comes down to isNat:

def isNat (s : String) : Bool :=
  s.all fun c => c.isDigit

def toNat? (s : String) : Option Nat :=
  if s.isNat then
    some <| s.foldl (fun n c => n*10 + (c.toNat - '0'.toNat)) 0
  else
    none

so one would have to add s.length > 0 to the isNat conditions.

Sebastian Ullrich (Jun 25 2022 at 16:34):

(or !s.isEmpty)

Sebastian Ullrich (Jun 25 2022 at 16:42):

fixed

Marcus Rossel (Aug 30 2023 at 05:43):

The same issue still exists for Substring:

def isNat (s : Substring) : Bool :=
  s.all fun c => c.isDigit

def toNat? (s : Substring) : Option Nat :=
  if s.isNat then
    some <| s.foldl (fun n c => n*10 + (c.toNat - '0'.toNat)) 0
  else
    none

Should this be adapted, too?


For comparison, here the implementation for String:


Last updated: Dec 20 2023 at 11:08 UTC