Haskell不同于Scala,是一门纯函数式语言,它强制使用者使用函数式语法而没有妥协。
在OS X下安装Haskell环境:brew install haskell-platform
通过命令启动交互式环境:ghci
{- basic type -}
Prelude> 4 * (5 + 1)
24
Prelude> "hello" ++ " world"
"hello world"
Prelude> ['a', 'b'] --list
"ab"
['a', 'b'] :: [Char]
Prelude> (1,2,3) --tuple
(1,2,3) :: (Num t, Num t1, Num t2) => (t, t1, t2)
Prelude> if (5 == 5) then "true" else "false""true"
"true"
{- var accessing -}
fst tuple
snd tuple
head list
last list
tail list
let (h:t) = [1, 2, 3, 4] {- h=1, t=[2,3,4] -}
1:[2,3,4] {- [1,2,3,4] -}
{- verbose type info -}
Prelude> :set +t
Prelude> :t 2
2 :: Num a => a
Prelude> (5 == (2 + 3))
True
it :: Bool
{- let binding -}
Prelude> let x = 10
x :: Integer
Prelude> let double x = x * 2
double :: Num a => a -> a
{- dot notation -}
Prelude> let second = f . g
Prelude> let second list = f (g list)
second :: [a] -> a
{- ./double.hs -}
module Main where
{- without type def -}
double x = x + x
{- with type def -}
double_int :: Integer -> Integer
double_int x = x + x
{- load .hs in GHCi -}
*Main> :load double.hs
*Main> double 2
4
Prelude> let fact x = if x == 0 then 1 else fact (x - 1) * x
{- ./fact_with_guards.hs -}
module Main where
fact :: Integer -> Integer
fact x
| x > 1 = x * fact(x - 1) {- sentinel -}
| otherwise = 1
{- ./fib_recusive.hs -}
module Main where
fib :: Integer -> Integer
fib 0 = 1
fib 1 = 1
fib x = fib(x - 1) + fib(x - 2)
{- ./fib_tuple.hs -}
module Main where
fibFast :: Integer -> Integer
fibFast x = fibResult(fibTuple(0,1,x))
fibTuple :: (Integer, Integer, Integer) -> (Integer, Integer, Integer)
fibTuple (x, y, 0) = (x, y, 0)
fibTuple (x, y, index) = fibTuple (y, x + y, index - 1)
fibResult :: (Integer, Integer, Integer) -> Integer
fibResult (x,y,z) = x
{- ./fib_pair.hs -}
module Main where
{- using Tuple-}
fibFast :: Integer -> Integer
fibFast = fst . fibNthPair
fibNextPair :: (Integer, Integer) -> (Integer, Integer)
fibNextPair (x, y) = fibNextPair (y, x + y)
fibNthPair :: Integer -> (Integer, Integer)
fibNthPair 1 = (1,1)
fibNthPair x = fibNextPair(fibNthPair(x-1))
通过let (h:t) = list
{- ./fib_pair.hs -}
module Main where
size [] = 0
size (h:t) = 1 + size (t)
prod [] = 1
prod (h:t) = h * prod (t)
1:[2,3,4] -> [1,2,3,4]
module Main where
allEven :: [Integer] -> [Integer]
allEven [] = []
allEven (h:t) = if even h then h:allEven t else allEven t
[1..10]
[10, 8 .. 4]
take 5 [0, 2 ..]
[x * 2 | x <- [1,2,3]]
[(y,x+1) | (x,y) <-[(1,2),(2,3),(3,4)]]
let crew = ["Spock", "Kirk", "McCoy"]
[(a,b) | a <- crew, b <- crew, a/=b] {- /= means not equal -}
module Main where
mulTable :: Integer -> [(Integer,Integer,Integer)]
mulTable 1 = mulTableRow 1
mulTable n = (mulTableRow n) ++ (mulTable (n-1))
mulTableRow :: Integer -> [(Integer,Integer,Integer)]
mulTableRow n = [(x,y,x*y) | x <- [n], y<-[1..n]]
{-
*Main> mulTable 2
[(2,1,2),(2,2,4),(1,1,1)]
-}
(\param1.. paramn ->function_body)
map (\x -> x * x) [1, 2, 3]
Prelude> filter odd [1, 2, 3, 4, 5]
[1,3,5]
Prelude> foldl (\x carryOver -> carryOver + x) 0 [1 .. 10]
55
Prelude> foldl1 (+) [1 .. 3]
6
{- haskell/map.hsmodule -}
module Main where
squareAllPlusOne list = map squarePlusOne list
where
squarePlusOne x = x * x + a
let a = 1
把多参数函数,拆分成多个只有一个参数的函数
Prelude> double x = x * x
double :: Num a => a -> a
Prelude> let prod x y = x * y
prod :: Num a => a -> a -> a
Prelude> let double = prod 2
double :: Integer -> Integer
{- my_range.hs -}
module Main where
myRange start step = start:(myRange (start + step) step)
{- lazy_fib.hs -}
module Main where
lazyFib x y = x:(lazyFib y (x + y))
fib = lazyFib 1 1
fibNth x = head (drop (x - 1) (take (x) fib))
{- cards.hs -}
module Main where
data Suit = Spades | Hearts deriving (Show)
data Rank = Ten | Jack | Queen | King | Ace deriving (Show)
type Card = (Rank, Suit)
type Hand = [Card]
value :: Rank -> Integer
value Ten = 1
value Jack = 2
value Queen = 3
value King = 4
value Ace = 5
cardValue :: Card -> Integer
cardValue (rank, suit) = value rank
--
*Main> cardValue (Ten, Hearts)
1
backwards :: [a] -> [a]
backwards [] = []
backwards (h:t) = backwards t ++ [h]
module Main where
data Triplet a = Trio a a a deriving (Show)
--
*Main> :t Trio
Trio :: a -> a -> a -> Triplet a
module Main where
data Tree a = Children [Tree a] | Leaf a deriving (Show)
-- 计算高度 --
depth (Leaf _) = 1
depth (Children c) = 1 + maximum (map depth c)
--
*Main> let leaf1 = Leaf 11
*Main> let leaf2 = Leaf 22
*Main> let tree = Children[Leaf 1, Leaf 2]
*Main> tree
Children [Leaf 1,Leaf 2]
非面向对象的类概念,它不涉及数据,可以精细控制重载和多态。
以下是 Eq 类的定义:
class Eq a where
(==), (/=) :: a -> a -> Bool
-- Minimal complete definition:
-- (==) or (/=)
x /= y = not (x == y)
x == y = not (x /= y)
类支持继承:
def treasure_map(v):
v = stagger(v)
v = stagger(v)
v = crawl(v)
return v
module Main where
stagger :: (Num t) => t -> t
stagger d = d + 2
crawl d = d + 1
treasureMap d =
crawl (stagger (stagger d))
module Main where
letTreasureMap (v,d) =
let d1 = stagger d
d2 = stagger d1
d3 = crawl d2
in d3
module Main where
data Position t = Position t deriving (Show)
stagger (Position d) = Position (d + 2)
crawl (Position d) = Position (d + 2)
rtn x = x -- packaging monad
x >>== f = f x -- bind
treasureMap pos = pos >>==
stagger >>==
stagger >>==
crawl >>==
rtn
--
*Main> treasureMap (Position 0)
5
module Main where
tryIo = do
putStr "Enter your name: " ;
line <- getLine ;
let { backwards = reverse line} ;
return ("Hello. Your backwards is " ++ backwards)
instance Monad [] where
m >>= f = concatMap f m
return x = [x]
module Main where
crack = do
x <- ['a'..'c']; y <- ['a'..'c']; z <- ['a'..'c'];
let {password = [x,y,z]};
if attempt password
then return (password, True)
else return (password, False)
attempt pw = if pw == "cab" then True else False
Maybe 能够解决一些函数返回失败,如数据库、网络、文件I/O等函数。
下面是 Just 定义:
{- Just 类似 Swift 的 Optional-}
Prelude> Just "some string"
Just "some string"
Prelude> Just Nothing
Just Nothing
Prelude> :t Just
Just :: a -> Maybe a
Prelude> :t Nothing
Nothing :: Maybe a
{- Def. of HTML handler -}
paragraph xmlDoc -> xmlDoc
body xmlDoc -> xmlDoc
html xmlDoc -> xmlDoc
进入正题,处理HTML文档,不用 Maybe Monad 时需要处理每层(paragraph / html / body)的 Nothing 异常:
用 Maybe Monad :
{- Without Maybe Usage-}
paragraph body (html xmldoc)
{- Without Maybe Implementation (trival in handling exception)-}
case (html doc) of
Nothing -> Nothing
Just x -> case body x of
Nothing -> Nothing
Just y -> paragraph 2 y
用 Maybe Monad :
{- Maybe Usage-}
Just someWebPage >>== html >>= body >>== paragraph >>== return
{- Def. of Maybe Monad -}
data Maybe a = Nothing | Just a
instance Monad Maybe where
return = Just
Nothing >>= f = Nothing
(Just x) >>= f = f x
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有