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

How can I refactor two functions into one function that takes a generic argument?

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

示例:

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 语句组成,其中 returns 适当的 post.

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

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

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

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

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

type PostType = Video | Podcast

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

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

或者,如果您选择将 post 主体与类型分开,您可以这样做:

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

type Post = Post PostType PostContents

而您的 getPostContents 函数将只是

getPostContents : Post -> PostContents
getPostContents _ contents =
    contents