簡體   English   中英

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

[英]Is it possible to have an if function use pattern matching in Haskell?

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

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

或者使用caselet (或者你可以內聯或使用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

圖案在函數定義匹配是用於通過提供的“基本的”圖案匹配簡單語法糖case 例如,讓我們去看你的第一個函數:

testingMethod [] = "Blank"
testingMethod (x:xs) = show x

可以改寫為:

testingMethod arg = case arg of
  [] -> "Blank"
  (x:xs) -> show x

你打算用你的第二個片段做什么並不是那么清楚,所以我無法真正向你展示它與case表達式的外觀。 但是一種可能的解釋是這樣的:

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

這假設你的function2返回兩個列表的元組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM