模式匹配Haskell中的字符串前缀

编程入门 行业动态 更新时间:2024-10-17 21:29:19
本文介绍了模式匹配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中的字符串前缀

本文发布于:2023-10-26 18:37:08,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:前缀   字符串   模式   Haskell

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!