Date
May. 19th, 2024
 
2024年 4月 12日

Post: Haskell Primer 006: 模式匹配

Haskell Primer 006: 模式匹配

Published 12:04 Apr 13, 2016.

Created by @ezra. Categorized in #Programming, and tagged as #Haskell.

Source format: Markdown

Table of Content

模式匹配主要用来定义一些数据必须遵循的规则,根据他们来解析数据。

例如:

sevencheck :: Integer -> Bool
sevencheck 7 = True
sevencheck x = False

head' [x] = x
head' [] = "error"
head' (x:_) x

你也可以对数据进行引用,可以添加 引用名称@:

firstletter :: String -> String
firstletter "" = "empty"
firstletter all@(x:_) = "first letter of " ++ all ++ " is " ++ [x]

where

首先要注意,在使用模式匹配时,where 只能被当前模式读取,而不能被其它模式所读取。

其次,在 where 中也可以使用模式匹配,例如:

firstLetterOfName :: String -> String -> String
firstLetterOfName firstname lastname = [f] ++ " " ++ [l]
    where (f:_) = firstname
          (l:_) = lastname

更进一步,你还可以定义函数:

calcarea :: [(Double, Double)] -> [Double]
calcarea l = [area w h | x > 0, y > 0]
    where area w h = w * h
Pinned Message
HOTODOGO
I'm looking for a SOFTWARE PROJECT DIRECTOR / SOFTWARE R&D DIRECTOR position in a fresh and dynamic company. I would like to gain the right experience and extend my skills while working in great teams and big projects.
Feel free to contact me.
For more information, please view online résumé or download PDF
本人正在寻求任职 软件项目经理 / 软件技术经理 岗位的机会, 希望加⼊某个新鲜⽽充满活⼒的公司。
如有意向请随时 与我联系
更多信息请 查阅在线简历下载 PDF