Haskell 中的交换函数

发布于 2024-12-07 13:16:31 字数 207 浏览 0 评论 0原文

我想在 haskell 中编写一个函数,它不介意我以什么顺序向它提供参数,例如,我想

    reproduce1 :: Male -> Female -> Child
    reproduce2 :: Female -> Male -> Child

通过一个函数“regenerate”来统一这两个函数。

I want to write a function in haskell which would not mind in what order I provide it its argument, for example, I want to unify these two functions

    reproduce1 :: Male -> Female -> Child
    reproduce2 :: Female -> Male -> Child

by one function 'reproduce'.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

九命猫 2024-12-14 13:16:31

您可以使用多参数类型类来完成此操作。

{-# LANGUAGE MultiParamTypeClasses #-}

class Reproduce x y where
  reproduce :: x -> y -> Child

instance Reproduce Male Female where
  reproduce = reproduce1

instance Reproduce Female Male where
  reproduce = reproduce2

不过,我很好奇您为什么要这样做。

You can do this using a multi-parameter type class.

{-# LANGUAGE MultiParamTypeClasses #-}

class Reproduce x y where
  reproduce :: x -> y -> Child

instance Reproduce Male Female where
  reproduce = reproduce1

instance Reproduce Female Male where
  reproduce = reproduce2

However, I'm curious about why you would want to do this.

两个我 2024-12-14 13:16:31

也许您想将参数打包成数据类型并使用记录 (参见“标记字段”)?

   data Args = A { m :: Male , f :: Female}
   reproduce :: Args -> Child

不过,我和@hammar 一样好奇。

Maybe you'd like to package your arguments into a datatype and use records (see "Labelled Fields") instead?

   data Args = A { m :: Male , f :: Female}
   reproduce :: Args -> Child

However, I share @hammar's curiosity.

情痴 2024-12-14 13:16:31

我正在考虑这样的事情,如果两个成年人的性别相同,则会抛出异常:

module Main where

main = putStrLn (reproduce (Male "a") (Female "b"))

type Child = String
data Adult = Male String | Female String
  deriving (Show)

reproduce :: Adult -> Adult -> Child
reproduce (Male a) (Female b) = a ++ "+" ++ b
reproduce (Female a) (Male b) = b ++ "+" ++ a

I was thinking about something like this, which throws an exception if both adults are of the same sex:

module Main where

main = putStrLn (reproduce (Male "a") (Female "b"))

type Child = String
data Adult = Male String | Female String
  deriving (Show)

reproduce :: Adult -> Adult -> Child
reproduce (Male a) (Female b) = a ++ "+" ++ b
reproduce (Female a) (Male b) = b ++ "+" ++ a
卷耳 2024-12-14 13:16:31

我强烈建议修复顺序,先说男性,然后是女性,或者像 ShiDoSi 的解决方案中那样创建“婚姻”数据类型。

但是,请检查论文第 12 页的“会话类型和对偶性”部分 “类型函数的乐趣” - 我认为这是一个很好的例子,您需要以对称方式耦合类型雌雄配对。

I strongly recommend fixing the order, say first Male and then Female, or making a "marriage" datatype as in ShiDoSi's solution.

However, check section "Session types and duality", pg 12 in the paper "Fun with type functions" - I think that is a good example where you need types coupled in symmetric pairs male-female.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文