Strings¶
Three small string functions, checked in strict mode and proven pure, and
all three compiled to native code: initials splits and uppercases,
is_palindrome indexes a string from both ends, and word_count counts
words into a dict. Python calls the first two natively. It calls
word_count on its Python body, and ppy explain says why.
Run it¶
What it prints¶
python strings.ppy, ppy strings.ppy, ppy run strings.ppy
Which functions lower¶
ppy explain strings.initials # llvm backend: native
ppy explain strings.is_palindrome # llvm backend: native
ppy explain strings.word_count # llvm backend: native; called from Python, its Python body runs: copying its strings across costs what one pass over them saves
is_palindrome indexes cleaned[left] and cleaned[right]. Natively a
string knows its length in code points and whether it is all ASCII, so an
index into ASCII text is one step, and the one-character strings the
comparison reads are static and never allocated.
word_count makes one pass over its text. Called from Python, the text
itself is borrowed, but every word in the dict it returns is a string
made natively and then decoded into a Python string, which costs about
what that one pass saves, so the cost model leaves Python's call on the
Python body; a native caller calls it natively. The
Strings example counts words over 200,000 lines,
where the work is worth the copy.
Very large text¶
Text of millions of characters can still come in as bytes:
Buffer[ppy.u8] is one byte per character and is read without building a
Python string, which is how
substring search scans four million
characters.
Where the code comes from¶
strings.ppy is hand-written; there is no .py source and no conversion step.
Read on: Strings · Reading input · Native lowering · Algorithms: substring search
19_strings/strings.ppy¶
import ppy
@ppy.pure
def initials(name: str) -> str:
out: str = ""
for part in name.split(" "):
if len(part) > 0:
out += part[0].upper()
return out
@ppy.pure
def is_palindrome(text: str) -> bool:
cleaned: str = text.lower().replace(" ", "")
left: int = 0
right: int = len(cleaned) - 1
while left < right:
if cleaned[left] != cleaned[right]:
return False
left += 1
right -= 1
return True
@ppy.pure
def word_count(text: str) -> dict[str, int]:
counts: dict[str, int] = {}
for word in text.lower().split(" "):
counts[word] = counts.get(word, 0) + 1
return counts
def main() -> None:
print(initials("ada lovelace king"))
print(is_palindrome("A man a plan a canal Panama"), is_palindrome("nope"))
print(sorted(word_count("a b a c b a").items()))
main()
Source: examples/19_strings.