验证输入参数的功能

时间:2018-08-02 09:56:19

标签: kdb

定义了验证输入参数的方法:

`validate_paramaters{[Date;Code;CodeType;Param]
 if[ not (14h=abs[type[Date]]);
      [
           .log.info["\tError - Exiting function - Date is not of the correct type"];
           : `$"Error - Date is not of the correct type"
         ]
       ];
if[ not (11h=abs[type[Code]]);
         [
           .log.info["\tError - Exiting function - Code is not of the correct type"];
           : `$"Error - Code is not of the correct type"
         ]
       ];
if[ not (-11h=type[CodeType]);
         [
           .log.info["\tError - Exiting function - CodeType is not of the correct type"];
           : $"Error - CodeType is not of the correct type"
         ]
       ];
:`validated

}`

但是现在CodeType的类型添加了更多的附加内容:

 -11h=type[CodeType] `also can be` 99h=type[CodeType]

请给我指导,我现在如何验证CodeType

2 个答案:

答案 0 :(得分:1)

not (-11h=type[CodeType])替换为not any -11 99h in type CodeType

关键字in允许您将CodeType的类型与数字类型的列表进行比较。这将返回一个布尔列表。例如:

q)CodeType:`sample`dictionary!`a`b
q)-11 99h in type CodeType
01b

如果列表中的任何成员为True,则在any之前添加1b

q)any -11 99h in type CodeType
1b

最后,如果CodeType不是上述类型之一,您似乎会抛出错误,因此我们将在所有这些前面加上not

答案 1 :(得分:1)

除了Jemma的回复,您还可以尝试一种更简洁的方法:

validate:{[d;names;types]
  if[count fails:key[d] where not any each types=type each d[names];
  :"error - exiting - ",("," sv string fails)," are not of correct type"];
 };

此函数的第一个参数是字典(d),其中键是参数的名称,值是其对应的值。该参数可以与您正在查询的变量的名称以及它们应为的类型一起传递。如果您要查找多种类型,则应使用嵌套列表。

例如,这是带有有效条目的字典。

q)d:`date`code`codetype!(.z.d;`some`code`to`test;`thetypeofmycode)
q)validate[d;`date`code`codetype;(-14;11;(-11 99h))]
q)

但是,如果用无效的数据类型更新字典,您会看到这将返回错误。

q)d[`code]:"wrongtype"
q)d[`date]:.z.p
q)validate[d;`date`code`codetype;(-14;11;(-11 99h))]
"error - exiting - date,code are not of correct type"

请注意,类型列表必须与字典顺序相同

要合并您的.log.info,可以按如下方式修改上述功能:

validate:{[d;names;types]if[count fails:key[d] where not any each types=type each d key d;
  .lg.info"error - exiting - ",("," sv string[fails])," are not of correct type";
  :"error: ",("," sv string[fails])," - type incorrect"]}

参考上面的示例,这将返回相同的结果,但是这次也使用.log.info记录错误。