scala - Scala 在 Haskell 中的部分函数
问题描述
Scala 对偏函数有很好的支持,主要是因为在 Scala 中,当你定义一个偏函数时,它也isDefinedAt
为它定义了一个函数。Scala 也有orElse
和andThen
函数一起使用部分函数。
Haskell 确实通过简单地非详尽地定义一个函数来支持部分函数(尽管在 Haskell 社区中强烈反对它们)。但是要定义isDefinedAt
一般的函数,您必须使用某种异常处理,我无法弄清楚。一旦isDefinedAt
定义了函数,那么它就可以用来定义orElse
并且andThen
函数已经存在了(.)
。
总之,我想定义一个函数,
isDefinedAt :: (a -> b) -> a -> Bool
isDefinedAt f x = -- returns True if f is defined at x else False
谁能告诉我如何编写这样的函数。
注意,我可以定义一个带有签名的函数
isDefinedAt :: (a -> b) -> a -> IO Bool
对于通用的b
. 但我想要一个没有 IO 在共同域中的功能。
关于 Scala 的 Partial Functions 的一篇不错的文章是 - How to create and use partial functions in Scala By Alvin Alexander
解决方案
我建议像在 Scala 中一样,为偏函数使用单独的类型。
import Control.Arrow
import Data.Maybe
type Partial = Kleisli Maybe
isDefinedAt :: Partial a b -> a -> Bool
isDefinedAt f x = isJust $ runKleisli f x
-- laziness should save some of the work, if possible
orElse :: Partial a b -> Partial a b -> Partial a b
orElse = (<+>)
andThen :: Partial a b -> Partial b c -> Partial a c
andThen = (>>>)
推荐阅读
- c# - 查找是否在 Azure 服务总线队列上启用了会话
- android - 如何查看有多少玩家在 Play 游戏服务中解锁了一项成就?
- arrays - 统一反序列化
- pytorch - 我应该如何理解 nn.Embeddings 参数 num_embeddings 和 embedding_dim?
- c++ - 我无法在 Win32 应用程序的工具栏按钮上设置自定义 ICO 图标
- excel - 公式函数内的循环变量
- python-3.x - “有没有办法在 Python 中创建元组列表的排列或乘积?”
- python-3.x - matplotlib 错误:没有名为 matplotlib 的模块,即使它已安装
- java - 通过 Java 字节码可以看到用值初始化的全局变量还是私有变量?
- netlogo - Netlogo - 海龟穿越线