进来的人在Elm中的绑定是否懒惰?

时间:2018-10-09 21:34:58

标签: lazy-evaluation elm let

我有两个功能A和B,可以同时禁用,启用A,启用B,但不能同时启用这两个功能。看完Making Impossible States Impossible后,我想尝试在类型级别上实施此操作。

我正在考虑的解决方案的简化版本如下。

module Main exposing (main)

import Browser
import Html exposing (Html, button, div, text)
import Html.Events exposing (onClick)

type Model
  = NoneEnabled
  | AEnabled
  | BEnabled

init : Model
init = NoneEnabled

type Msg
  = EnableA
  | DisableA
  | EnableB
  | DisableB

view : Model -> Html Msg
view model =
  let -- Buttons to enable and disable features
      buttons =
        div [] [ button [onClick EnableA] [text "Enable A"]
               , button [onClick DisableA] [text "Disable A"]
               , button [onClick EnableB] [text "Enable B"]
               , button [onClick DisableB] [text "Disable B"]
               ]

      -- All possible feature states
      aEnabled  = div [] [text "A enabled"]
      aDisabled = div [] [text "A disabled"]
      bEnabled  = div [] [text "B enabled"]
      bDisabled = div [] [text "B disabled"]
  in case model of
       NoneEnabled ->
         div [] [buttons, aDisabled, bDisabled]
       AEnabled ->
         div [] [buttons, aEnabled, bDisabled]
       BEnabled ->
         div [] [buttons, aDisabled, bEnabled]

update : Msg -> Model -> Model
update msg model =
  case (msg, model) of
    (EnableA, _) ->
      AEnabled
    (EnableB, _) ->
      BEnabled
    (DisableA, AEnabled) ->
      NoneEnabled
    (DisableB, BEnabled) ->
      NoneEnabled
    _ ->
      model

main : Program () Model Msg
main =
  Browser.sandbox { init = init, update = update, view = view }

aEnabled中我的aDisabledbEnabledbDisabledview功能可能计算起来很昂贵。是否会评估它们而与case model of哪个分支无关,还是只能依靠正在评估的已使用功能?

或者用一个简短的例子来表达。

f c x =
  let a = x + 1
      b = x + 2
  in case c of
       True ->
         a
       False ->
         b

f True 0是否会在let表达式中强制对b进行求值?

1 个答案:

答案 0 :(得分:5)

Elm的let / in语句不会被懒惰地求值。您可以输入一些Debug.log语句来证明这一点:

f c x =
  let a = Debug.log "a calculated" <| x + 1
      b = Debug.log "b calculated" <| x + 2
  in case c of
       True ->
         a
       False ->
         b

仅调用一次f会将两条消息记录到控制台,无论输入如何。 Example here

一种解决此障碍的方法是要求ab使用任意参数,例如单位()

f c x =
  let a () = Debug.log "a calculated" <| x + 1
      b () = Debug.log "b calculated" <| x + 2
  in case c of
       True ->
         a ()
       False ->
         b ()

此变体仅评估函数a b