七周七语言之Haskell代码学习

来源:互联网 发布:网络美术培训 编辑:程序博客网 时间:2024/05/18 01:50
-- hello_world.hsmodule Main where  -- 创建Main模块(它是顶级模块),模块用于将相关代码放到一个相同的作用域中  main = putStrLn "Hello World"--command模式<img src="http://img.blog.csdn.net/20150101001036165" alt="" />-- 实现斐波那契-- 实现1module Main where  fib :: Integer -> Integer  --定义了fib函数,该函数接收一个整型参数并返回一个整型值  fib 0 = 1  fib 1 = 1  fib x = fib (x - 1) + fib (x - 2)-- 实现2-使用元组(由括号内以逗号分隔的元素组成)module Main where  fibTuple :: (Integer, Integer, Integer) -> (Integer, Integer, Integer)  fibTuple (x, y, 0) = (x, y , 0)  fibTuple (x, y, index) = fibTuple (x, x + y, index - 1)  fibResult :: (Integer, Integer, Integer) -> Integer  fibResult (x, y, z) = x  fib :: Integer -> Integer  fib x = fibResult (fibTuple (0, 1, x))-- 实现3-使用元组和组合module Main where  fibNextPair :: (Integer, Integer) -> (Integer, Integer)  fibNextPair (x, y) = (y, x + y)  fibNthPair :: Integer -> (Integer,Integer)  fibNthPair 1 = (1, 1)  fibNthPair n = fibNextPair (fibNthPair (n - 1))  fib :: Integer -> Integer  fib = fst . fibNthPair  -- 函数组合,使用fibNthPair构建一个二元组,fst抓取第一个元素-- 惰性机制-- lazy_fib.hsmodule Main where  lazyFib x y = x:(lazyFib y (x + y))  fib = lazyFib 1 1  fibNth x = head (drop (x - 1) (take (x) fib)) -- head表示取头部,drop表示删除前多少个-- command<img src="http://img.blog.csdn.net/20150101001042218" alt="" />-- monad:是一个类型构造器,包括了一些用于包装和将函数串联在一起的函数。-- monad三个基本组成:一个基于某容器类型的类型构造器;一个名为return的函数,负责将一个函数包装起来并放入容器;一个名为>>=的bind函数,负责给函数解包。-- 一个海盗有一张藏宝图,在喝醉酒状态下,他只能走两步(stagger)、爬一步(crawl)的从起点向终点靠近。-- monad.hs,重新构建一个monadmodule Main where  -- 类型构造器  data Position t = Position t deriving (Show)  -- 在声明用户自定义类型的时候,需要继承show函数  -- 函数  stagger (Position d) = Position (d + 2)  crawl (Position d) = Position (d + 1)  -- 使用rtn、>>==是为了防止与内置的monad函数发生冲突  -- return值  rtn x = x  -- bind函数  x >>== f = f x  treasureMap pos = pos >>==                    stagger >>==                    stagger >>==                    crawl >>==                    rtn-- 使用monad和do记号实现简易的密码破解功能-- password.hsmodule 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<pre name="code" class="plain" style="font-size: 14px; line-height: 21px;">-- command




优势:
1.类型系统:Haskell是强类型,但是可以方便的将新行为与新类型关联到一起,并且你可以从头开始创建一个高级类型。
2.表现力:拥有丰富的函数库和功能强大的语法,在学术环境中,你可能再也找不到比Haskell更强大的函数式编程语言了。
3.编程模型的纯洁性:给定相同的输入,函数将总是返回相同的结果,这个属性是的程序推导变得更加容易。
4.惰性机制:支持惰性机制,能够更方便的进行编程。
5.学术支持:Haskell是函数式编程技术的主要教学语言。

不足:
1.编程模型不灵活:作为一门纯函数式编程语言,Haskell不适合I/O密集和脚本任务。
2.社区:Haskell与Scala具有不同的设计哲学,前者一切都是关于纯洁的,后者一切都是关于妥协的。但是Haskell的社区发展落后与Scala社区。
3.学习曲线:Haskell中monad、柯里化等概念都是需要拥有牢固理论基础的程序员才能熟练应用,学习曲线比普通的编程语言较陡。
0 0