有没有办法在Ada的String变量中按名称调用过程,就像Python一样:
def _ssh(hostname, port):
pass
def _telnet(hostname, port):
pass
def _mosh(hostname, port):
pass
protocols = {
'ssh': _ssh,
'mosh': _mosh,
'telnet': _telnet
}
# call your function by string
hostname = 'localhost'
port = '22'
protocol = 'ssh'
result = protocols[protocol](hostname, port)
Run Code Online (Sandbox Code Playgroud)
嗯,这有点工作,因为你没有任何方便的简写来创建地图(又名字典).这样做的工作:
with Ada.Containers.Indefinite_Ordered_Maps;
with Ada.Text_IO; use Ada.Text_IO;
procedure Alubio is
Run Code Online (Sandbox Code Playgroud)
我们需要一个指向子程序的指针来实例化Map
type Handler is access procedure (Hostname : String; Port : Integer);
Run Code Online (Sandbox Code Playgroud)
从字符串到指针到子程序的映射.它需要是"无限期",因为String类型是不定的(不是固定大小),它需要"有序",因为我们不想要声明散列函数等等.
package Maps is new Ada.Containers.Indefinite_Ordered_Maps
(Key_Type => String,
Element_Type => Handler);
Run Code Online (Sandbox Code Playgroud)
我喜欢在定义子程序之前声明子程序,但这里并不是绝对必要的
procedure Ssh (Hostname : String; Port : Integer);
procedure Mosh (Hostname : String; Port : Integer);
procedure Telnet (Hostname : String; Port : Integer);
Run Code Online (Sandbox Code Playgroud)
地图
Map : Maps.Map;
Run Code Online (Sandbox Code Playgroud)
演示子程序
procedure Ssh (Hostname : String; Port : Integer) is
begin
Put_Line ("ssh, " & Hostname & Port'Image);
end Ssh;
procedure Mosh (Hostname : String; Port : Integer) is
begin
Put_Line ("mosh, " & Hostname & Port'Image);
end Mosh;
procedure Telnet (Hostname : String; Port : Integer) is
begin
Put_Line ("telnet, " & Hostname & Port'Image);
end Telnet;
begin
Run Code Online (Sandbox Code Playgroud)
设置地图
Map.Insert ("ssh", Ssh'Access);
Map.Insert ("mosh", Mosh'Access);
Map.Insert ("telnet", Telnet'Access);
Run Code Online (Sandbox Code Playgroud)
通过Map调用子程序.你不太确定为什么需要.all(取消引用指向子程序的指针),你常常不这样做:在没有它的情况下,编译器说"无效程序或入口调用",指向Map.
Map ("ssh").all ("s", 1);
Map ("mosh").all ("m", 2);
Map ("telnet").all ("t", 3);
end Alubio;
Run Code Online (Sandbox Code Playgroud)
输出:
$ ./alubio
ssh, s 1
mosh, m 2
telnet, t 3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
110 次 |
| 最近记录: |