read

前陣子經 Jemery Lu 大大介紹了好書,(又)開始不務正業唸起了 Haskell。看到一段程式碼深切感受到 Haskell 的美感。因此想試著來解釋一下它有趣的地方。

原程式碼:

replaceWithP :: a -> Char
replaceWithP = const 'p'

lms :: [Maybe [Char]]
lms = [Just "Ave", Nothing, Just "woohoo"]

-- replace all
replaceWithP lms -- => 'p'

-- lift once
fmap replaceWithP lms -- => "ppp", or say ['p', 'p', 'p']

-- lift twice
(fmap . fmap) replaceWithP lms -- => [Just 'p', Nothing, Just 'p']

-- lift thrice
(fmap . fmap . fmap) replaceWithP lms -- => [Just "ppp", Nothing, Just "pppppp"]

在 Haskell 裡

有一些簡單的事情

  1. String 是 List of chart
  2. List 的每個元素都要是同一個型別

也有稍微要習慣一下的東西

Happy hacking!

Blog Logo

taiansu


Published

Image

Tai-An Su

So Wrong, It's Right.

Back to Overview