在Elm中,是否有合并合并类型的方法? (出于模块化目的) [英] In Elm, is there a way to merge union types ? (for modularity purpose)
问题描述
从这三个声明开始:
type SharedMsg
= SharedAction
type Page1Msg
= Page1Action
type Page2Msg
= Page2Action
我有没有办法获得下一个的等价物?像合并"联合类型的方法一样?
I there a way to obtain an equivalent of the following one? Like a way to "merge" union types ?
type Msg
= SharedAction
| Page1Action
| Page2Action
============================
=============================
上下文:我正在将Elm应用程序分成每页一个模块,每个模块都有自己的文件夹.
Context : I am splitting an Elm application into one module per page with their own folders.
某些操作将被共享,而某些操作将是特定于页面的.
Some actions will be shared, and some actions will be page-specific.
如果要使用Html.map
方法,我觉得我将不得不重写页面以其自身的PageMsg
消息类型使用的每个共享操作:
If I was to use the Html.map
method, I feel that I would have to re-write every shared action that a page uses in its own PageMsg
message type:
type Page1Msg
= Page1Action
| SharedAction
type Msg
= Page1Msg Page1Msg
| Page2Msg Page2Msg
view : Model -> Html Msg
view =
Html.map Page1Msg (Page1View.view model)
因此,我想对所有页面使用唯一的Msg
类型,但是通过在其自己的文件夹中写入特定于页面的消息来保持模块化,然后通过合并它们以某种方式定义唯一的Msg
类型.
Hence my thinking of using a unique Msg
type for all pages, but preserving modularity by writing page-specific messages in their own folders, and then somehow defining a unique Msg
type by merging them.
推荐答案
@ z5h的答案几乎是正确的,但是类型构造函数必须具有不同的名称.
@z5h's answer is almost correct, but the type constructors have to have different names.
您无法按照自己的方式合并类型.
对于惯用方式:您将拆分类型命名为Msg
,而不是Page1Msg
.因此,例如:
As for the idiomatic way: You would name the split types just Msg
, not Page1Msg
. So, for example:
Page1.elm:
module Page1 exposing (Msg)
type Msg
= Foo
Page2.elm:
module Page2 exposing (Msg)
type Msg
= Bar
Shared.elm:
module Shared exposing (Msg)
type Msg
= Baz
Main.elm:
module Main exposing (..)
import Shared
import Page1
import Page2
type Msg
= SomethingCustom
| SharedMsg Shared.Msg
| Page1Msg Page1.Msg
| Page2Msg Page2.Msg
顺便说一句,请记住,如果将模块分为Page1.View
,Page1.Types
等,则只要公开的功能不重叠,就可以使用相同的名称导入不同的模块,即:
By the way, remember that if you split the modules into Page1.View
, Page1.Types
, etc., then as long as the exposed functions don't overlap, you can import different modules under the same name, ie:
import Page1.Types as Page1
import Page1.State as Page1
import Page1.View as Page1
import Page1.Decoders as Page1
这篇关于在Elm中,是否有合并合并类型的方法? (出于模块化目的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!