ska*_*ith 4 haskell functional-programming matching
我知道采用列表输入的方法可以使用模式匹配,如下所示:
testingMethod [] = "Blank"
testingMethod (x:xs) = show x
我的问题是,我可以使用if函数吗?例如,如果我有一个需要检查function2输出模式的function1,我该怎么做呢?我正在寻找这样的东西:
if (function2 inputInt == pattern((x:xs), [1,2,3])) then
这有可能在哈斯克尔做吗?
您正在寻找的语法是case语句或guard:
你说:
if (function2 inputInt == pattern((x:xs), [1,2,3])) then
在Haskell:
testingMethod inputInt | (x:xs, [1,2,3]) <- function2 inputInt = expr
                       | otherwise = expr2
或者使用case和let(或者你可以内联或使用where):
testingMethod inputInt =
    let res = function2 inputInt
    in case res of
         (x:xs, [1,2,3]) -> expr
         _ -> expr2
或使用视图模式:
{-# LANGUAGE ViewPatterns #-}
testingMethod (function2 -> (x:xs,[1,2,3])) = expr
testingMethod _ = expr2