惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

罗磊的独立博客
Apple Machine Learning Research
Apple Machine Learning Research
The Cloudflare Blog
WordPress大学
WordPress大学
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 叶小钗
博客园 - 聂微东
阮一峰的网络日志
阮一峰的网络日志
腾讯CDC
博客园 - 三生石上(FineUI控件)
V
V2EX
有赞技术团队
有赞技术团队
V
Visual Studio Blog
小众软件
小众软件
Jina AI
Jina AI
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - Franky
量子位
T
Tailwind CSS Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
P
Palo Alto Networks Blog
Cisco Talos Blog
Cisco Talos Blog
I
Intezer
Project Zero
Project Zero
A
Arctic Wolf
P
Privacy International News Feed
V
Vulnerabilities – Threatpost
L
Lohrmann on Cybersecurity
S
Securelist
C
Cybersecurity and Infrastructure Security Agency CISA
C
CXSECURITY Database RSS Feed - CXSecurity.com
T
Tor Project blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
S
Security @ Cisco Blogs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Google DeepMind News
Google DeepMind News
N
News and Events Feed by Topic
TaoSecurity Blog
TaoSecurity Blog
L
LINUX DO - 热门话题
G
GRAHAM CLULEY
Help Net Security
Help Net Security
N
News | PayPal Newsroom
W
WeLiveSecurity
G
Google Developers Blog
Microsoft Security Blog
Microsoft Security Blog
Engineering at Meta
Engineering at Meta
MongoDB | Blog
MongoDB | Blog
C
Check Point Blog

Jiajun的技术笔记

你好,2026! TiDB 源码阅读(六):TiDB Coprocessor 源码解析 性能优化的核心思想 TiDB 源码阅读(五):索引 TiDB 源码阅读(四):AST、逻辑计划、物理计划 CockroachDB Serverless Architecture podman 无故退出 Cursor Control-L (CTRL-L) Keyboard Shortcuts in Terminal Replace docker with podman Using xmonad with xfce4 A RC script for freebsd frpc 自己动手写一个k8s controller AI 会取代你的(编程)岗位吗? 自建DERP服务器提升Tailscale连接速度(使用Nginx转发) 自动升级Docker容器 再读《程序员修炼之道-从小工到专家》 让浏览器下载文件 再读《软件随想录》/《黑客与画家》/《软技能》 HTTP 压力测试中的 Coordinated Omission 2的补码 编程语言中的 context 是什么? flutter macOS 构建出错 Flatpak 使用小记 Golang CAS 操作是怎么实现的 PostgreSQL 当MQ来使用 Clash 结合 工作VPN 的网络设计 使用 PostgreSQL 搭建 JuiceFS PostgreSQL 配置优化和日志分析 有GitHub Copilot?那就可以搭建你的ChatGPT4服务 窗口函数的使用(以PG为例) 读《为什么学生不喜欢上学》 OpenAI Prompt Engineering 摘录和总结 读《打造真正的新产品》 VueJS 总结 Linux 自动挂载 alist 提供的webdav FreeBSD 使用 vm-bhyve 安装Debian虚拟机 FreeBSD 和 Linux 网卡聚合实现提速 GPT 帮我搞定了时区转换问题 长任务系统如何处理? macOS/Linux 编译 InputLeap 使用开源软KVM - synergy-core 解决 macOS 终端hostname一直变化问题 KVM 共享 Intel 集成显卡 PromQL 备忘 读《格鲁夫给经理人的第一课》 读《打开心智》 为什么要把复杂的联表操作拆成多个单表查询? 红包系统的设计 MySQL Index Condition Pushdown Optimization Go mod 简明教程 OpenWRT 使用 Android/iOS USB 网络 搭建旁路由 Golang gRPC 错误处理 编写可维护的单元测试代码 OAuth 2 详解(六):Authorization Code Flow with PKCE OAuth 2 详解(五):Device Authorization Flow OAuth 2 详解(三):Resource Owner Password Credentials Grant OAuth 2 详解(四):Client Credentials Flow OAuth 2 详解(二):Implict Grant Flow OAuth 2 详解(一):简介及 Authorization Code 模式 ElasticSearch 学习笔记 三种git流程以及发版模型 错误处理实践 权限模型(RBAC/ABAC) OIDC(OpenID Connect) 简介 任务队列简介 PostgreSQL 操作笔记 使用Drone CI构建CI/CD系统 Golang migrate 做数据库变更管理 使用PostgreSQL做搜索引擎 Nginx 源码阅读(三): 连接池、内存池 Nginx 源码阅读(二): 请求处理 Nginx 源码阅读(一): 启动流程 Go 泛型简明教程 KVM 显卡穿透给 Windows 使用 HTTP Router 处理 Telegram Bot 按钮回调 使用反射(reflect)对结构体赋值 GIN 是如何绑定参数的 你好 2022(2021 年终总结) 用Go导入大型CSV到PostgreSQL 使用 OpenWRT 搭建软路由 使用软KVM切换器 barrier 共享键鼠 SQL 防注入及原理 使用 gomock 测试 Go 代码 gevent不是黑魔法(二): gevent 实现 gevent不是黑魔法(一): greenlet 实现 用 entgo 替代 gorm 应用内使用crontab不是那么方便 单测时要不要 mock 数据库? Sentry 自建指南 用selenium完成自动化任务 用闲置的安卓手机做垃圾电话短信过滤 推荐三个时间管理工具 一次事故反思 当JS遇到uint64:JS整数溢出问题 SQLite3 存储以及ACID原理 Redis源码阅读:pub/sub实现 Redis源码阅读:zset实现 Redis源码阅读:bitmap 位图的运算 Redis源码阅读:set是怎么做交并集运算的?
Haskell TypeClass 笔记
2016-05-05 · via Jiajun的技术笔记

这是Haskell Wiki上的 一篇文章 <http://wiki.haskell.org/Typeclassopedia>_ ,以下是我的学习笔记。

学好Haskell有两个重点:

  • Understand the types

  • Gain a deep intuition for each type class and its relationship to other type classes, backed up by familiarity with many examples.

Haskell的类型系统如下图所示:

.. image:: https://wiki.haskell.org/wikiupload/d/df/Typeclassopedia-diagram.png

其中:

  • 实线箭头,如图中Functor指向Applicative的箭头,表示 Applicative包含于Functor

  • 虚线箭头,如图中Applicative指向Traversable,表示 其他的某种关系

  • Monad和ArrowApply是相等的

  • Semigroup, Apply, Comonad 尚未包含在标准库中

另外,不要被Haskell中的class关键字迷惑了,其实不是类,更像是 Java中的Interface。

Functor

Functor的定义如下:

.. code:: haskell

class Functor f where
    fmap :: (a -> b) -> f a -> f b

个人以为,用盒子来描述Functor非常合适,符合Functor的实例 都能进行fmap,而这个fmap能改变盒子里的内容但是不改变盒子的 结构,例如Maybe是Functor:

.. code:: haskell

data MyMaybe a = MyNothing | MyJust a deriving (Show, Eq)

instance Functor MyMaybe where
    fmap g MyNothing = MyNothing
    fmap g (MyJust a) = MyJust (g a)

.. code:: bash

# ghci
Prelude> :l fun.hs
Main> fmap (+1) (MyJust 1)
MyJust 2

现在我们回到fmap上来,其类型为::

fmap :: (a -> b) -> f a -> f b

其中 f a 整体作为一个类型,那么 f 便是一个 类型构造子(type constructor)。也就是说,作为Functor 的instance,必须是接受且仅接受一个参数。

常见的instance有 Either e , ((,) e) , ((->) e) , IO , 还有许多容器类型如 Tree, Map等。

Functor Laws


- fmap id = id

- fmap (g . h) = (fmap g) . (fmap h)

这两条在一起保证了fmap g不会改变容器而只改变其中的内容。
`其中第一条是第二条的充分不必要条件 <https://github.com/quchen/articles/blob/master/second_functor_law.md>`__ 。

Applicative
-------------

Applicative 介于Functor和Monad之间,对于Functor,fmap可以
把 *普通函数* 作用于容器内的内容。而Applicative为我们提供了
``<*>`` 来一个 *在容器内的函数* 作用于容器内的内容
(``<*>`` 读作"apply"),另外还有一个函数,``pure`` 可以把
参数加入到容器内。看Applicative的定义:

.. code:: haskell

    class Functor f => Applicative f where
        pure :: a -> f a
        infixl 4 <*>
        (<*>) :: f (a -> b) -> f a -> f b

如上,Applicative必定属于Functor。这里的f也是一个类型构造子
(type constructor)。

.. code:: haskell

    data MyMaybe a = MyNothing | MyJust a deriving (Show, Eq)

    instance Functor MyMaybe where
        fmap g MyNothing = MyNothing
        fmap g (MyJust a) = MyJust (g a)

    instance Applicative MyMaybe where
        pure = MyJust
        MyNothing <*> _ = MyNothing
        (MyJust f) <*> box = fmap f box

.. code:: bash

    [root@arch haskell]# ghci
    GHCi, version 7.10.3: http://www.haskell.org/ghc/  :? for help
    Prelude> :l fun.hs
    [1 of 1] Compiling Main             ( fun.hs, interpreted )
    Ok, modules loaded: Main.
    Main> pure (+) <*> MyJust 1 <*> MyJust 2
    MyJust 3

Applicative Laws
~~~~~~~~~~~~~~~~~

- The identity law::

    pure id <*> v = v

- Homomorphism(同态性)::

    pure f <*> pure x = pure (f x)

- Interchange(交换性)::

    u <*> pure y = pure ($ y) <*> u

- Composition(组合)::

    u <*> (v <*> w) = pure (.) <*> u <*> v <*> w

另外,在 ``Control.Applicative`` 中定义了 ``<$>`` ,相当于
fmap::

    g <$> x = pure g <*> x

It says that mapping a pure function g over a context x
is the same as first injecting g into a context with pure,
and then applying it to x with (<*>).

Monad
-------

首先来看Monad的定义:

.. code:: haskell

    class Applicative m => Monad m where
        return :: a -> m a
        (>>=) :: m a -> (a -> m b) -> m b
        (>>) :: m a -> m b -> m b
        m >> n = m >>= \_ -> n

        fail :: String -> m a

其中的return就是pure,从其他编程语言过来的人一定要注意不要混淆。
``>>`` 是 ``>>=`` 的一种特殊情况,看上面的默认实现就知道了,另外,
``m >> n`` ignores the result of m, but not its effects.

    在这里我们可以对比一下Functor,Applicative,Monad三者,继续以
    容器为例,fmap的类型为 ``fmap :: (a -> b) -> f a -> f b`` 即把
    一个容器内的内容作用于普通函数;而 ``<*>`` 的类型为
    ``(<*>) :: Applicative f => f (a -> b) -> f a -> f b`` 即把一个
    在容器内的内容作用于在容器内的函数;而 ``>>=`` 的类型为
    ``(>>=) :: Monad m => m a -> (a -> m b) -> m b`` 即把一个容器内的内容
    作用于一个接受普通参数但产生容器类型的函数。Haskell的好处便在这里有了
    体现,我们可以直接通过看函数的类型签名来判断函数的作用,却不需要查看
    函数的具体实现。

接下来把上面自己定义的MyMaybe实现为Monad的实例:

.. code:: haskell

    data MyMaybe a = MyNothing | MyJust a deriving (Show, Eq)

    instance Functor MyMaybe where
        fmap g MyNothing = MyNothing
        fmap g (MyJust a) = MyJust (g a)

    instance Applicative MyMaybe where
        pure = MyJust
        MyNothing <*> _ = MyNothing
        (MyJust f) <*> box = fmap f box

    instance Monad MyMaybe where
        return a = MyJust a

        MyNothing >>= _ = MyNothing
        (MyJust a) >>= f = f a

.. code:: bash

    Main> MyJust 1 >>= (\p -> (MyJust (10+p)))
    MyJust 11
    Main> MyNothing >>= (\p -> (MyJust (10+p)))
    MyNothing
    Main> MyNothing >> MyJust 1 >>= (\p -> (MyJust (10+p)))
    MyNothing

more about >>=
~~~~~~~~~~~~~~~~

``>>=`` 通常读作 "bind"。The basic intuition is that it combines two
computations into one larger computation. In other words, x >>= k is
a computation which runs x, and then uses the result(s) of x to decide
what computation to run second, using the output of the second
computation as the result of the entire computation.

详见原文5.3节,其中有包括用 fmap, pure, <*> 实现 >>= 的介绍。

Monad Laws
~~~~~~~~~~~~

- ``return a >>= k = k a``

- ``m >>= return = m``

- ``m >>= (\k -> k x >> h) = (m >>= k) >>= h``

do notation

do 是Haskell中提供的一种语法糖,让程序看起来更像是命令式编程风格。 原文中介绍了do的缩进或者括号风格,还是直接看 Haskell Report 2010中的相关介绍吧 <https://www.haskell.org/onlinereport/haskell2010/haskellch10.html#x17-17800010.3>__ 。