Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
是否可以在Haskell中使用if函数进行模式匹配?_Haskell_Functional Programming_Matching - Fatal编程技术网

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

是否可以在Haskell中使用if函数进行模式匹配?,haskell,functional-programming,matching,Haskell,Functional Programming,Matching,我知道接受列表输入的方法可以使用模式匹配,如下所示: testingMethod [] = "Blank" testingMethod (x:xs) = show x 我的问题是,我可以用if函数来实现吗?例如,如果我有一个function1需要检查function2输出的模式,我将如何进行这项工作?我在找这样的东西: if (function2 inputInt == pattern((x:xs), [1,2,3])) then case function2 inputInt of (

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

testingMethod [] = "Blank"
testingMethod (x:xs) = show x
我的问题是,我可以用if函数来实现吗?例如,如果我有一个function1需要检查function2输出的模式,我将如何进行这项工作?我在找这样的东西:

if (function2 inputInt == pattern((x:xs), [1,2,3])) then
case function2 inputInt of
  ((x:xs), [1,2,3]) -> -- ...
  (_, _) -> -- ...

在haskell中可以这样做吗?

您要查找的语法是case语句或guard:

你说:

if (function2 inputInt == pattern((x:xs), [1,2,3])) then
在哈斯克尔:

testingMethod inputInt | (x:xs, [1,2,3]) <- function2 inputInt = expr
                       | otherwise = expr2
或使用视图模式:

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

函数定义中的模式匹配只是
case
提供的“基本”模式匹配的语法糖分。例如,让我们对第一个函数进行消噪:

testingMethod [] = "Blank"
testingMethod (x:xs) = show x
可以重写为:

testingMethod arg = case arg of
  [] -> "Blank"
  (x:xs) -> show x
您的第二个代码片段打算做什么还不太清楚,因此我无法真正向您展示使用
case
表达式时它的外观。但一种可能的解释是:

if (function2 inputInt == pattern((x:xs), [1,2,3])) then
case function2 inputInt of
  ((x:xs), [1,2,3]) -> -- ...
  (_, _) -> -- ...

这假设你的
函数2
返回一个由两个列表组成的元组。

你可以使用一个模式保护。而且
(==)
不起作用,因为
(==)
实际上“只是一个普通函数”(当然有一些限制)。@WillemVanOnsem哇,我以前没听说过这些,这很酷,我只在使用
模式同义词时才使用视图模式,而且每次都要查找语法。我绝对讨厌这些东西,希望我们有更好的选择。还有
多路if