是否可以在Haskell中使用if函数使用模式匹配?

ska*_*ith 4 haskell functional-programming matching

我知道采用列表输入的方法可以使用模式匹配,如下所示:

testingMethod [] = "Blank"
testingMethod (x:xs) = show x
Run Code Online (Sandbox Code Playgroud)

我的问题是,我可以使用if函数吗?例如,如果我有一个需要检查function2输出模式的function1,我该怎么做呢?我正在寻找这样的东西:

if (function2 inputInt == pattern((x:xs), [1,2,3])) then
Run Code Online (Sandbox Code Playgroud)

这有可能在哈斯克尔做吗?

Tho*_*son 6

您正在寻找的语法是case语句或guard:

你说:

if (function2 inputInt == pattern((x:xs), [1,2,3])) then
Run Code Online (Sandbox Code Playgroud)

在Haskell:

testingMethod inputInt | (x:xs, [1,2,3]) <- function2 inputInt = expr
                       | otherwise = expr2
Run Code Online (Sandbox Code Playgroud)

或者使用caselet(或者你可以内联或使用where):

testingMethod inputInt =
    let res = function2 inputInt
    in case res of
         (x:xs, [1,2,3]) -> expr
         _ -> expr2
Run Code Online (Sandbox Code Playgroud)

或使用视图模式:

{-# LANGUAGE ViewPatterns #-}
testingMethod (function2 -> (x:xs,[1,2,3])) = expr
testingMethod _ = expr2
Run Code Online (Sandbox Code Playgroud)