0

除了模式保护之外,为什么不使用谓词保护?

{-# 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
4

2 回答 2

3

您的第一个建议是有效的语法,所以只需使用它:

main = print $ case toLower <$> os of
  x | "mingw" `isPrefixOf` x -> "windows"
    | "darwin" == x          -> "mac"
    | otherwise              -> "linux"
于 2014-10-03T07:44:11.483 回答
0

编辑:我以为你的目标是不惜一切代价获得一个无积分的案例。正如 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")]
于 2014-10-03T07:39:40.120 回答