You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在SWI-Prolog中获取数字字母混合项的ASCII值列表

Converting Mixed Alphanumeric Terms to ASCII Value Lists in SWI-Prolog 7.6.3

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 (like abc123 or 123xyz). 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/2 for numbers if you want to distinguish between the numeric value and its character representation—use number_codes/2 instead for pure numbers.

内容的提问来源于stack exchange,提问作者Iqazra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:12:43