在SWI-Prolog中获取数字字母混合项的ASCII值列表
Hey there! Let's break down how to handle converting those mixed letter-and-number terms into their corresponding ASCII value lists in SWI-Prolog 7.6.3. I see you already know the basics with name/2 for pure letters or numbers—great, we can build right on that.
First, Let's Clarify "Mixed Alphanumeric Terms" in Prolog
In SWI-Prolog, any term that mixes letters and numbers (like abc123, 123xyz, or foo42bar) is treated as an atom (unless it's wrapped in double quotes, which makes it a string). Pure numbers are integers/floats, but once you add letters, it becomes an atom.
Using name/2 (The One You Already Know)
Good news: name/2 works perfectly for mixed alphanumeric atoms too! It converts the atom (or string, or number) directly into a list of ASCII codes. For example:
% For a mixed atom like abc123 ?- name(abc123, ASCIIList). ASCIIList = [97, 98, 99, 49, 50, 51]. % For a mixed string (double quotes) ?- name("Hello123!", ASCIIList). ASCIIList = [72, 101, 108, 108, 111, 49, 50, 51, 33].
The predicate handles the mix seamlessly—each character (whether letter or digit) gets converted to its ASCII equivalent.
Better Alternatives: Type-Specific Predicates
While name/2 is convenient, modern Prolog recommends using more explicit predicates to avoid ambiguity. Here are the go-tos:
atom_codes/2: For atoms (likeabc123or123xyz). It's strictly for atoms, so you don't have to worry about accidental type conversions:?- atom_codes(123xyz, ASCIIList). ASCIIList = [49, 50, 51, 120, 121, 122]. % Reverse: Convert ASCII list back to an atom ?- atom_codes(MyAtom, [49, 50, 51, 97, 98, 99]). MyAtom = 123abc.string_codes/2: For string literals (wrapped in double quotes). This is ideal if you're working with string types directly:?- string_codes("FooBar456", ASCIIList). ASCIIList = [70, 111, 111, 66, 97, 114, 52, 53, 54].
Key Notes to Remember
- If you have user input that's a mix of letters and numbers, make sure it's parsed as an atom or string first (Prolog will usually do this automatically unless it's a pure number).
- Avoid using
name/2for numbers if you want to distinguish between the numeric value and its character representation—usenumber_codes/2instead for pure numbers.
内容的提问来源于stack exchange,提问作者Iqazra

