如何验证Haskell“公共安全”构造函数的参数?

时间:2015-11-14 20:50:10

标签: python-2.7 validation haskell assertions

在我的Python package我有一个函数,我用它来创建我的类的验证实例,类似

@staticmethod
def config_enigma(rotor_names, window_letters, plugs, rings):

    comps = (rotor_names + '-' + plugs).split('-')[::-1]
    winds = [num_A0(c) for c in 'A' + window_letters + 'A'][::-1]
    rngs = [int(x) for x in ('01.' + rings + '.01').split('.')][::-1]

    assert all(name in rotors for name in comps[1:-1])
    assert comps[-1] in reflectors
    assert len(rngs) == len(winds) == len(comps)
    assert all(1 <= rng <= 26 for rng in rngs)
    assert all(chr_A0(wind) in LETTERS for wind in winds)

    #...

我想在Haskell中强制执行相同的行为。但是以相同的方式这样做 - 使用断言 - 不起作用,因为Haskell断言一般被禁用(unless certain compiler flags are set)。例如,在something like

configEnigma rots winds plug rngs =
    assert ((and $ (==(length components')) <$> [length winds', length rngs']) &&
            (and $ [(>=1),(<=26)] <*> rngs') &&
            (and $ (`elem` letters) <$> winds') &&
            (and $ (`M.member` comps) <$> tail components'))
    -- ...
    where
        rngs' = reverse $ (read <$> (splitOn "." $ "01." ++ rngs ++ ".01") :: [Int])
        winds' = "A" ++ reverse winds ++ "A"
        components' = reverse $ splitOn "-" $ rots ++ "-" ++ plug

不能依赖于工作,因为断言将在大多数情况下被删除。

什么是强制所有实例在Haskell中验证的惯用且可靠的方法(使用“公共安全”构造函数)?

1 个答案:

答案 0 :(得分:5)

正常的事情是明确地表达失败。例如,可以写一个

configEnigma :: ... -> Maybe ...
configEnigma ... = do
    guard (all (((==) `on` length) components') [winds', rngs'])
    guard (all (inRange (1,26)) rngs')
    guard (all (`elem` letters) winds')
    guard (all (`M.member` comps) (tail components'))
    return ...
    where
    ...

对于某些自定义类型Maybe,您甚至可以考虑从Except Error升级到Error,以便向调用者传达构建期间出错的内容。然后,您可以使用类似以下的结构而不是guard

    unless (all (inRange (1,26)) rngs') (throwError OutOfRange)

configEnigma的来电者必须表达如何处理失败。对于Maybe,这看起来像

case configEnigma ... of
    Just v  -> -- use the configured enigma machine v
    Nothing -> -- failure case; perhaps print a message to the user and quit

Except同时,您可以获得有关错误的信息:

case runExcept (configEnigma ...) of
    Right v  -> -- use the configured enigma machine v
    Left err -> -- failure case; tell the user exactly what went wrong based on err and then quit