《Haskell趣學指南》筆記之模塊

系列文章數組


目前咱們提到的全部函數、type 和 typeclass 都是 Prelude 模塊的一部分,默認狀況下,Prelude 模塊會被自動導入。函數

導入模塊

import ModuleName-- 導入模塊的語句必須防止在函數定義以前
import Data.List (nubsort) -- 只導入兩個函數
import Data.List hiding (nub) -- 不導入 nub
import qualified Data.Map -- 只能使用 Data.map.xxx 來使用函數
import qualified Data.Map as M -- 只能使用 M.xxx 來使用函數
複製代碼

導入以後,該模塊的全部函數就都進入了『全局』命名空間。post

要查看函數位於哪一個模塊,能夠用 Hoogle (www.haskell.org/hoogle/)。spa

在 GHCi 中導入模塊的語句是:3d

ghci> :m + Data.List Data.Map Date.Set
複製代碼

細節:點號既能夠用於命名空間,又能夠用於組合。怎麼區分呢?當點號位於限定導入的模塊名與函數中間且沒有空格時,會被視做函數引用; 不然會被視做函數組合。code

Data.List 模塊

  • words -- 取出字符串裏面的單詞,組成字符串列表
  • group / sort / tails / isPrefixOf / any / isInfixOf 是否含於
  • foldl' 不延遲的 foldl
  • find / lookup

例子:ci

import Data.List 
wordNums :: String -> [(String, Int)] 
wordNums = map (\ws -> (head ws, length ws)) . group . sort . words
複製代碼

Data.Char 模塊

  • ord 'a' -- 97
  • chr 97 -- 'a'

Maybe 類型

findKey :: (Eq k) => k -> [(k, v)] -> Maybe v 
findKey key [] = Nothing 
findKey key ((k, v): xs)    
    | key == x = Just v    
    | otherwise = findKey key xs 
複製代碼

注意 Maybe / Nothing / Just 這三個東西。字符串

Data.Map 模塊

  • API: fromList / insert / size / fromListWith

使用示例get

import qualified Data. Map as Map 
phoneBook :: Map. Map String String 
phoneBook = Map. fromList $    
[(" betty", "555- 2938")    
,(" bonnie", "452- 2928")    
,(" patsy", "493- 2928")    
,(" lucille", "205- 2928")    
,(" wendy", "939- 8282")    
,(" penny", "853- 2492")]

ghci> :t Map. lookup
Map. lookup :: (Ord k) => k -> Map. Map k a -> Maybe a 
ghci> Map. lookup "betty" phoneBook 
Just "555- 2938" 
ghci> Map. lookup "wendy" phoneBook 
Just "939- 8282" 
ghci> Map. lookup "grace" phoneBook 
Nothing
複製代碼

自定義模塊

普通模塊string

  1. 新建 Geometry.hs

  2. 寫文件

    module Geometry ( 
     sphereVolume , 
     sphereArea 
     ) where 
    
     sphereVolume :: Float -> Float 
     sphereVolume radius = (4.0 / 3.0) * pi * (radius ^ 3) 
     sphereArea :: Float -> Float 
     sphereArea radius = 4 * pi * (radius ^ 2)
    複製代碼
  3. 在同一目錄的其餘文件裏引入模塊 import Geometry

有層次的模塊

  1. 新建 Geometry 目錄

  2. 在 Geometry 目錄裏面新建 Sphere.hs / Cuboid.hs / Cube.hs

  3. 這三個文件的內容相似這樣

    module Geometry.Sphere ( 
     volume , 
     area 
     ) 
     where 
     
     volume :: Float -> Float 
     volume radius = (4.0 / 3.0) * pi * (radius ^ 3) 
     area :: Float -> Float 
     area radius = 4 * pi * (radius ^ 2)
    複製代碼
  4. 在 Geometry 目錄的同級文件中導入模塊 import Geometry.Sphere

相關文章
相關標籤/搜索