列表的第一个和最后一个项目的模式匹配

Kev*_*ith 3 haskell

是否可以在"开头f",然后是任何文本上进行模式匹配,并以"结尾b

我试过了:

f :: String -> Bool
f ('f':xs:'b') = True
f _            = False
Run Code Online (Sandbox Code Playgroud)

但是我收到了一个错误:

explore/PatternMatching.hs:2:11:
    Couldn't match expected type ‘[Char]’ with actual type ‘Char’
    In the pattern: 'b'
    In the pattern: xs : 'b'
    In the pattern: 'f' : xs : 'b'
Failed, modules loaded: none.
Run Code Online (Sandbox Code Playgroud)

ely*_*ely 7

没有模式匹配语言扩展,没有简单的方法可以做到这一点.我会把它写成:

f :: String -> Bool
f str = case (take 1 str, drop (length str - 1) str) of
    ("f", "b") -> True
    otherwise -> False
Run Code Online (Sandbox Code Playgroud)

(使用takedrop避免特殊处理空字符串的情况,在使用例如head或时可能导致错误!!)

Prelude> f "flub"
True
Prelude> f "foo"
False
Prelude> f "fb"
True
Prelude> f "fbbbb"
True
Prelude> f "fbbbbf"
False
Prelude> f ""
False
Run Code Online (Sandbox Code Playgroud)