如何将两个函数重构为一个具有泛型参数的函数?
例:
getVideo : Video -> Post
getVideo video =
let
(Video post) =
video
in
post
getPodcast : Podcast -> Post
getPodcast podcast =
let
(Podcast post) =
podcast
in
post
Run Code Online (Sandbox Code Playgroud)
我想做这样的事情:
getPodcast : 'a -> Post
getPodcast 'a =
let
('a post) =
'a
in
post
Run Code Online (Sandbox Code Playgroud)
附录:
type Video
= Video Post
type Podcast
= Podcast Post
Run Code Online (Sandbox Code Playgroud)
你不能在Elm中拥有这样一个开放式的泛型函数.这有两个选择:
您可以创建一个容器类型,其中包含每个有效类型的构造函数:
type PostContainer
= VideoContainer Video
| PodcastContainer Podcast
Run Code Online (Sandbox Code Playgroud)
现在你的getPost函数包含一个case返回相应帖子的语句.
getPost : PostContainer -> Post
getPost container =
case container of
VideoContainer (Video post) ->
post
PodcastContainer (Podcast post) ->
post
Run Code Online (Sandbox Code Playgroud)
Post值中包含帖子类型假设您的Post对象如下所示:
type alias Post =
{ name : String
, body : String
}
Run Code Online (Sandbox Code Playgroud)
你可以像这样创建一个post类型的枚举:
type PostType = Video | Podcast
Run Code Online (Sandbox Code Playgroud)
您可以重新定义Post以包含类型:
type alias Post =
{ name : String
, body : String
, postType : PostType
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您选择将帖子主体与类型分开,则可以执行以下操作:
type alias PostContents =
{ name : String
, body : String
}
type Post = Post PostType PostContents
Run Code Online (Sandbox Code Playgroud)
而你的getPostContents功能就是
getPostContents : Post -> PostContents
getPostContents _ contents =
contents
Run Code Online (Sandbox Code Playgroud)