now, we will see how we make monads,.
the guideline of making hte monad is not to make a monad for the purpose of monad. normally, we usually make a type that whose purpose is to model an aspect of some problem and then later on if we see that the type represents a value with a context and can act like a monad, we give it a Monad instance.
as agin, we will use some real examples to show the idea.
suppose that we have a list of [3,5,9], and when we feed that to the >>= operator, we will just all the possible choice of taking an element from teh list adn applying the function to it and then presents the rsult in a list as well.
there is no information telling the possiblity of each of those number's occuring. suppose that we want to have 50% percent for the appearance of 3, and 25% each of 5, and 9.. so we might get the following structure.
[(3,0.5),(5,0.25),(9,0.25)]
Haskell offers us a type for rational types, it is "Rational" and lives in "Data.Ratio", we write it as if it were a fraction, the numerator and the denominator are separated by a %, here are a few examples.
ghci> 1%4 1 % 4 ghci> 1%2 + 1%2 1 % 1 ghci> 1%3 + 5%4 19 % 12
so the number wil be represented as below.
ghci> [(3,1%2),(5,1%4),(9,1%4)] [(3,1 % 2),(5,1 % 4),(9,1 % 4)]
to better represent that we will create a new type, and the type is called Prob which takes a parameter, a,
here it is.
import Data.Ratio newtype Prob a = Prob { getProb :: [(a,Rational)] } deriving Show
next is to consider whether or not to make it a functor, the list is a functor, so probably it is good to make it part of functor, but we are only interested in the number itself, and we will leave the possiblity as they are.
instance Functor Prob where fmap f (Prob xs) = Prob $ map (\(x,p) -> (f x,p)) xs
Now the big question, is this a monad?return x is supposed to make a monadic value that always presents x as its result, so it doesn't make sense for the probability to be 0. If it always has to present it as its result, the probability should be 1!
What about >>=? so let's make use of the fact that m >>= f always equals join (fmap f m) for monads and think about how we would flatten a probability list of probability lists.
Here's this situation expressed as a probability list:
thisSituation :: Prob (Prob Char) thisSituation = Prob [( Prob [('a',1%2),('b',1%2)] , 1%4 ) ,( Prob [('c',1%2),('d',1%2)] , 3%4) ]
and we must invent some way to calculate the possiblity of individuals under a possiblity group, and here is it.
flatten :: Prob (Prob a) -> Prob a flatten (Prob xs) = Prob $ concat $ map multAll xs where multAll (Prob innerxs,p) = map (\(x,r) -> (x,p*r)) innerxs
what it does for the multAll is to take a possibility p and applies that to each of the possiblty of the inner possibility group with p, return a list of items and new possiblity.
now, we have all that, now let's make a monad instance out of it.
instance Monad Prob where return x = Prob [(x,1%1)] m >>= f = flatten (fmap f m) fail _ = Prob []
the reason to return 1 as the possibility is because when a item happens, you know for sure that the possibility is 1. we uses flattern because we already have a jon method named, and the flattern method has the ability to calculate conditional possibility . and when it fails, it shall return a empty list.
there is a very important point of writing haskell monad, you might want to verify that monad that you write conforms to the monad rules. the rules that we shall verify include: 1. return and then fmap , the possibility should be 1 %1 multply the possiblity returned by f; 2. f <=< (g <=h ) should be the same as (f <=< g) <=< h, this holds as well, because it holds for the list monads which forms the basis of hte possiblity monad.
Now, we have the monad, what can we do with it?
Say we have two normal coins and one loaded coin that gets tails an astounding nine times out of ten and heads only one time out of ten. If we throw all the coins at once, what are the odds of all of them landing tails? First, let's make probability values for a normal coin flip and for a loaded one:
data Coin = Heads | Tails deriving (Show, Eq) coin :: Prob Coin coin = Prob [(Heads,1%2),(Tails,1%2)] loadedCoin :: Prob Coin loadedCoin = Prob [(Heads,1%10),(Tails,9%10)]
and finally, the coin throwing actions.
import Data.List (all) flipThree :: Prob Bool flipThree = do a <- coin b <- coin c <- loadedCoin return (all (==Tails) [a,b,c])
Giving a go, we see te odds of all three landing tails are not that good, despites cheating with our laoded coin:
ghci> getProb flipThree [(False,1 % 40),(False,9 % 40),(False,1 % 40),(False,9 % 40), (False,1 % 40),(False,9 % 40),(False,1 % 40),(True,9 % 40)]
we know that even with the loade coin, we are not that lucky to get a wiin.
In this post, we went from having a question (what if lists also carried information about probability?) to making a type, recognizing a monad and finally making an instance and doing something with it. I think that's quite fetching! By now, we should have a pretty good grasp on monads and what they're about.
相关推荐
Atom-ide-haskell-hoogle 是一个专门为 Atom 编辑器设计的插件,它整合了 Haskell 的 Hoogle 工具,以提供强大的代码提示和搜索功能。Atom 是一款由 GitHub 开发的开源文本编辑器,它利用现代 web 技术如 HTML、CSS ...
在 Emacs 中,`haskell-mode` 是一个专门为了提升 Haskell 开发体验而设计的模式。 `haskell-mode` 提供了多种增强功能,旨在帮助 Haskell 开发者更高效地编写、调试和理解代码。这个模式包括以下关键特性: 1. **...
在数据可视化领域,`haskell-chart`库提供了一种高效且灵活的方式来创建2D图表,这对于数据分析、科学计算以及教学等场景非常有用。这个库是开源的,意味着任何人都可以查看其源代码,学习并贡献改进。 `haskell-...
**哈斯克尔编程语言与Atom-Haskell-GHC-Mod** 哈斯克尔(Haskell)是一种纯函数式编程语言,以其优雅的语法、强静态类型系统和编译时优化而受到程序员的喜爱。它鼓励使用不可变数据和惰性求值,这使得哈斯克尔在...
Atom-Haskell-Debug是针对Haskell开发者的一个强大工具,它允许你在流行的Atom文本编辑器中集成一个图形化的Haskell调试器。这个工具基于GHCi(Glasgow Haskell Compiler Interface),GHCi是Haskell的交互式环境,...
Haskell-Data-Analysis-Cookbook, Haskell数据分析 cookbook的附带源代码 Haskell-Data-Analysis-Cookbook这是 Haskell数据分析 cookbook的附带源代码。最新的源代码可以在GitHub上获得: ...
从1.0.0开始,haskell-ghc-mod提供haskell-completion-backend服务。 注意:在1.0.0之前,提供了ide-backend服务。 它已被废弃以支持ide-haskell的UPI。 您可以在找到描述 执照 版权所有:copyright:2015 Atom-...
haskell-ghc-mod原子包 该软件包主要用作后端。 Haskell ghc-mod打开通往ghc-modi的管道,并查询类型,信息并检查错误。 安装与配置 请参考官方文档站点 服务中心API 从1.0.0版本开始,haskell-ghc-mod提供...
Get Programming with HASKELL-2018-英文版
Haskell Monads小书 :warning: 初稿! –请仔细阅读 1. do块 2.解释嵌套的Lambda和绑定 =<<作为序列运算符 2C 。 a- a -> M b背后的直觉 2D合成do块 2E 。 嵌套do块 3.实现Monad和封装 3A 。 新型和副...
用于 haskell-relational-record 的 MySQL 驱动程序 这个项目被合并到 。 准备 $ git clone git@github.com:khibino/haskell-relational-record.git $ git clone git@github.com:bos/hdbc-mysql.git $ git clone ...
【标题】:“Atom-atom-haskell-scry,扩散系数.zip” 涉及的主要知识点是 Atom 编辑器与 Haskell 语言的集成以及 SCRY 工具的使用。 【描述】:“Atom-atom-haskell-scry.zip”的描述指出,这个压缩包包含了一个名...
Atom-ide-haskell-repl是针对Atom文本编辑器的一个扩展插件,专为Haskell编程语言提供集成的GHCi(Glasgow Haskell Compiler Interface)交互式环境,即REPL(Read-Eval-Print Loop)。这个插件允许开发者在Atom编辑...
在Haskell的世界里,开发环境的配置至关重要,而`haskell-dev-tools`就是一个方便的元项目,它专门设计用于简化Haskell开发工具的安装和升级过程。这个项目扮演了一个集合和自动化工具的角色,使得开发者无需手动...
Haskell-dap是一个开源项目,它实现了调试适应性协议(Debug Adapter Protocol,简称DAP)的接口,使得Haskell开发者可以充分利用这个协议进行程序调试。DAP是一个通用的、跨平台的协议,允许IDEs(集成开发环境)和...
你可以在找到 haskell-brainfuck用法图书馆 import HaskBF.Evalimport qualified Data.ByteString.Lazy as BSimport Control.Monad.Statemain = do -- The following will evaluate the file using stdin and ...
"haskell-tools"就是这样一个项目,它专注于为Haskell开发者提供一系列实用的辅助工具,以优化他们的开发流程。 ### 1. GHC:Glasgow Haskell Compiler GHC是Haskell的主要编译器,也是haskell-tools的重要组成...
### 函数式编程:Haskell到Java的转换 #### 概述 本文旨在探讨函数式编程语言Haskell如何被编译或转换为Java语言。Haskell作为一种纯函数式编程语言,以其强大的类型系统、惰性求值机制以及高度抽象的能力在学术界...
### Haskell - The Craft of Functional Programming #### 一、概述 《Haskell - The Craft of Functional Programming》是一本深入探讨Haskell编程语言的经典著作。本书由Tantanoid编写,并于1999年由Addison-...
Monads是Haskell处理副作用和控制流的一种抽象方式,是Haskell的一大特色。书中逐步介绍了Monad的概念,包括Maybe Monad用于处理可能的空值,IO Monad用于处理输入/输出操作。 9. 并发与并行 由于Haskell的纯函数...