模式匹配Haskell中的字符串前缀 [英] Pattern matching string prefixes in Haskell

查看:274
本文介绍了模式匹配Haskell中的字符串前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想为匹配以字符Z开头的字符串的函数做一个特例。

  myfunc('Z':restOfString)=  - 我可以使用模式匹配来轻松完成这项工作,做一些特别的事情
myfunc s = - 在这里做默认情况

但是如果我想匹配具有更长前缀的字符串?假设我想为以烤面包机一词开头的字符串开一个特例。什么是编写匹配这样一个字符串的模式的最佳方式?

解决方案

  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 here

But 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 here

Using 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 here

A 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中的字符串前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆