首页 > 解决方案 > Scala 在 Haskell 中的部分函数

问题描述

Scala 对偏函数有很好的支持,主要是因为在 Scala 中,当你定义一个偏函数时,它也isDefinedAt为它定义了一个函数。Scala 也有orElseandThen函数一起使用部分函数。

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

标签: scalahaskellpartial-functions

解决方案


我建议像在 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 = (>>>)

推荐阅读