gpt4 book ai didi

elm - 如何将两个函数重构为一个接受通用参数的函数?

转载 作者:行者123 更新时间:2023-12-05 00:22:18 25 4
gpt4 key购买 nike

如何将两个函数重构为一个具有泛型参数的函数?

示例:

getVideo : Video -> Post
getVideo video =
let
(Video post) =
video
in
post


getPodcast : Podcast -> Post
getPodcast podcast =
let
(Podcast post) =
podcast
in
post

我想做这样的事情:

getPodcast : 'a -> Post
getPodcast 'a =
let
('a post) =
'a
in
post

附录:

type Video
= Video Post

type Podcast
= Podcast Post

最佳答案

在 Elm 中不能有这样一个开放式的泛型函数。这里有两个选项:

  1. 使用容器类型

您可以创建一个容器类型,它的每个有效类型都有一个构造函数:

type PostContainer
= VideoContainer Video
| PodcastContainer Podcast

现在您的 getPost 函数包含一个 case 语句,它返回适当的帖子。

getPost : PostContainer -> Post
getPost container =
case container of
VideoContainer (Video post) ->
post

PodcastContainer (Podcast post) ->
post
  1. Post 值中包含帖子类型

假设您的 Post 对象如下所示:

type alias Post =
{ name : String
, body : String
}

您可以像这样创建帖子类型的枚举:

type PostType = Video | Podcast

您可以重新定义 Post 以包含以下类型:

type alias Post =
{ name : String
, body : String
, postType : PostType
}

或者,如果您选择将帖子正文与类型分开,您可以这样做:

type alias PostContents =
{ name : String
, body : String
}

type Post = Post PostType PostContents

而您的getPostContents 函数就是

getPostContents : Post -> PostContents
getPostContents _ contents =
contents

关于elm - 如何将两个函数重构为一个接受通用参数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44368578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com