-
-
Save bacwyls/8c268b0d64b5d52bb160ead7ad6e9068 to your computer and use it in GitHub Desktop.
stevelacy/go-urbit noun from string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func IsStrAtom(str string) bool { | |
for _, c := range str { | |
if !unicode.IsDigit(c) { | |
return false | |
} | |
} | |
return true | |
} | |
// is this string noun an explicit cell? | |
// explicit: begins and ends with [ and ] respectively | |
// and has valid inner brackets | |
func IsStrXCell(str string) bool { | |
if str[0] != '[' { | |
return false | |
} | |
brax := 0 | |
for i, c := range str { | |
if c == '[' { | |
brax += 1 | |
} | |
if c == ']' { | |
brax -= 1 | |
} | |
if brax == 0 { | |
return i == len(str)-1 | |
} | |
} | |
return false | |
} | |
// return split index | |
func SplitStrCell(str string) int { | |
brax := 0 | |
for i, c := range str { | |
if c == '[' { | |
brax += 1 | |
} | |
if c == ']' { | |
brax -= 1 | |
} | |
if c == ' ' && brax == 0 { | |
return i | |
} | |
} | |
// TODO error here | |
return -99 | |
} | |
func NounFromString(str string) Noun { | |
if IsStrAtom(str) { | |
i, err := strconv.ParseInt(str, 10, 64) | |
if err != nil { | |
bi := B(0) | |
bi, ok := bi.SetString(str, 10) | |
if !ok { | |
fmt.Println("SetString: error") | |
panic(err) | |
} | |
return MakeNoun(bi) | |
} | |
return MakeNoun(i) | |
} | |
if IsStrXCell(str) { | |
str = str[1 : len(str)-1] | |
} | |
split := SplitStrCell(str) | |
headRes := NounFromString(str[:split]) | |
tailRes := NounFromString(str[split+1:]) | |
res := MakeNoun([]interface{}{headRes, tailRes}) | |
return res | |
} | |
// example: | |
// n := NounFromString("[[[1 1] [2 2]] 2 2]") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment