为什么不在模式保护之外使用谓词保护呢?
{-# LANGUAGE MultiWayIf, LambdaCase #-}
module Main where
import System.Info (os)
import Control.Applicative ((<$>))
import Data.Char (toLower)
import Data.List (isPrefixOf)
main :: IO ()
main = print . ($ toLower <$> os) $ x -> if
| "mingw" `isPrefixOf` x -> "windows"
| "darwin" == x -> "mac"
| otherwise -> "linux"
会更漂亮:
main = print $ case toLower <$> os of
x | "mingw" `isPrefixOf` x -> "windows"
| "darwin" == x -> "mac"
| otherwise -> "linux"
甚至:
main = print $ case toLower <$> os of
| ("mingw" `isPrefixOf`) -> "windows"
| ("darwin" ==) -> "mac"
| otherwise -> "linux" -- when pattern absent: otherwise = const True
您的第一个建议是有效的语法,所以只需使用它:
main = print $ case toLower <$> os of
x | "mingw" `isPrefixOf` x -> "windows"
| "darwin" == x -> "mac"
| otherwise -> "linux"
编辑:我以为你的目标是不惜一切代价获得无点案例。正如安德拉斯·科瓦茨(András Kovács)所指出的,你的有针对性的建议确实是正确的语法。
这是一个毫无意义的风格匹配:
{-# LANGUAGE ViewPatterns #-}
main = print $ case toLower <$> os of
(("mingw" `isPrefixOf`) -> True) -> "windows"
(("darwin" ==) -> True) -> "mac"
_ -> "linux"
甚至,没有视图模式:
match :: a -> [(a -> Bool, b)] -> b
match x ((f,y):rest) | f x = y
| otherwise = match x rest
match _ [] = error "Non exhaustive predicates"
main = print $ match (toLower <$> os)
[(("mingw" `isPrefixOf`) , "windows")
,(("darwin"==) , "mac")
,((const True) , "linux")]