但是如果我想匹配具有更长前缀的字符串?假设我想为以烤面包机一词开头的字符串开一个特例。什么是编写匹配这样一个字符串的模式的最佳方式?
解决方案myfunc 't':'o':'a':'s':'t':'e':'r':restOfString)= ...
使用正常的模式匹配可以工作,但会因为前缀字符串变长而受到影响。
{ - #LANGUAGE PatternGuards# - } 导入Data.List myFunc字符串| just restOfString< - stripPrefixtoasterstring = - 做一些特殊的事情 myFunc string = - 在这里做默认情况使用库函数而不是模式匹配可以更容易读取和写入。
{ - #LANGUAGE ViewPatterns# - } import Data.List myFunc(stripPrefixtoaster - >只是restOfString)= - 做一些特殊的事情 myFunc string = - 在这里做默认情况GHC 6.10语法扩展使得这个用法更加自然。 p>
当然,后两者完全相同,我们可以在没有糖的情况下(混乱地) p>
import Data.List myFunc string = if restIsJust then - 做一些特殊的事情 else - 在此默认情况下其中(restIsJust,restOfString)= case stripPrefixtoaster字符串只是一些 - > (确实如此) Nothing - > (False,undefined)虽然这些语法扩展是为了让我们的生活更轻松。 p>
Let's say I want to make a special case for a function that matches strings that start with the character 'Z'. I could easily do it using pattern matching by doing something like the following:
myfunc ('Z' : restOfString) = -- do something special myfunc s = -- do the default case hereBut what if I want to match strings with a longer prefix? Say I want to have a special case for strings that start with the word "toaster". What's the best way to write a pattern to match such a string?
解决方案 myfunc ('t':'o':'a':'s':'t':'e':'r' : restOfString) = ...Using a normal pattern match works, but gets bothersome as the prefix string gets longer.
{-# LANGUAGE PatternGuards #-} import Data.List myFunc string | Just restOfString <- stripPrefix "toaster" string = -- do something special myFunc string = -- do the default case hereUsing a library function instead of a pattern match is a bit easier to read and write.
{-# LANGUAGE ViewPatterns #-} import Data.List myFunc (stripPrefix "toaster" -> Just restOfString) = -- do something special myFunc string = -- do the default case hereA GHC 6.10 syntax extension makes this usage even more natural.
Of course, the latter two are completely equivalent, and we can make do (messily) without any sugar at all.
import Data.List myFunc string = if restIsJust then -- do something special else -- do the default case here where (restIsJust, restOfString) = case stripPrefix "toaster" string of Just something -> (True, something) Nothing -> (False, undefined)Those syntax extensions are meant to make life easier for us, though.
更多推荐
模式匹配Haskell中的字符串前缀
发布评论