Elm 中的建模关联导致依赖循环

Modelling association in Elm leads to dependencies cycle

我的数据库由 table 个项目和 table 个相关广告组成。

我希望我的 elm 应用程序显示一个项目及其相关广告,或者一个包含父项目信息的广告。

为了满足这些接口需求,我希望在 elm 中编写以下两个模块,以匹配我的 API 已经发送的内容:

module Item.Model exposing (..)

import Ad.Model exposing (Ad)

type alias Item =
   { ads : Maybe List Ad
   }

module Ad.Model exposing (..)

import Item.Model exposing (Item)

type alias Ad =
   { item : Maybe Item
   }

然而,此定义会导致以下依赖项循环错误:

ERROR in ./elm-admin/Main.elm
Module build failed: Error: Compiler process exited with error Compilation failed
Your dependencies form a cycle:

  ┌─────┐
  │    Item.Model
  │     ↓
  │    Ad.Model
  └─────┘

You may need to move some values to a new module to get rid of the cycle.

    at ChildProcess.<anonymous> (/opt/app/assets/node_modules/node-elm-compiler/index.js:141:27)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at maybeClose (internal/child_process.js:886:16)
    at Socket.<anonymous> (internal/child_process.js:342:11)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at Pipe._handle.close [as _onclose] (net.js:497:12)
 @ ./js/admin.js 3:12-44

看起来在同一模块中同时定义 type alias 不会使编译器停止,但这对我来说不是一个令人满意的解决方案,因为我不希望我的每个 Model应用程序最终会出现在同一个文件中。

有没有办法在不在同一模块中定义两个类型别名 AdItem 的情况下解决这个问题?

我想不出你提出的问题的直接解决方案,但我不会那样存储数据 - 我会改用指针

module Item.Model exposing (..)

type alias Items = Dict String Item

type alias Item =
   { ads : List String
   }
   -- you don't need a Maybe and a List 
   -- as the absence of data can be conveyed by the empty list

module Ad.Model exposing (..)

import Item.Model exposing (Item)

type alias Ads = Dict String Ad 

type alias Ad =
   { itemKey : Maybe String
   }

然后你可以像

model.ads 
    |> L.filterMap (\key -> Dict.get key model.items)
    |> ...

model.itemKey
    |> Maybe.andThen (\itemKey -> Dict.get itemKey model.ads)
    |> ...

这样的方法行得通,而且还提供了后续记忆的机会