我有类似的,
type Post
= Blog String String
| Announcement String String
和功能一样,
upcaseTitle : Post -> Post
upcaseTitle post =
case post of
Blog title body ->
{ post | title = String.toUpper title }
Announcement title body ->
{ post | title = String.toUpper title }
我想写代码,
upcaseTitle : Post -> Post
upcaseTitle post =
case post of
Post title body ->
{ post | title = String.toUpper title }
我想在我的case
语句中添加一个与所有Post
类型匹配的子句,并提取常见的String
,title
,因为它在我的union类型的所有变体中共享。
榆树有可能吗?
不,不可能。在其他一些语言中,这可以使用or-patterns实现(即使这样你仍然需要枚举和解构每个变体,但它们可以共享一个单体),但Elm旨在成为一种比那些更简单的语言。
一种选择是将公共分支体提取为函数:
upcaseTitle : Post -> Post
upcaseTitle post =
let
setTitle title =
{ post | title = String.toUpper title }
in
case post of
Blog title body ->
setTitle title
Announcement title body ->
setTitle title
另一个是定义一个单独的函数来提取标题:
getTitle : Post -> String
getTitle post =
case post of
Blog title body ->
title
Announcement title body ->
title
upcaseTitle : Post -> Post
upcaseTitle post =
{ post | title = String.toUpper (getTitle post) }
但是,如果您的自定义类型的每个变体都相同,那么我首先会质疑该类型的设计。也许最好使用一个记录,其中帖子类型只是一个字段而不是?
type PostType
= Blog
| Announcement
type Post =
{ title : String
, body : String
, postType : PostType
}