0

我想在 Elm 中创建一个需要 4 个必需输入的表单:

  • 3 个浮点值
  • 1 个输入可以采用“长”或“短”的值(大概),这将是一个下拉菜单

输入值后,将进行计算,根据这些值产生单行输出。

我有这个作为命令行 Python 程序工作:

#!/usr/bin/env python


from __future__ import print_function

# core
import logging

# pypi
import argh

# local

logging.basicConfig(
    format='%(lineno)s %(message)s',
    level=logging.WARN
)

def main(direction, entry, swing, atr):

    entry = float(entry)
    swing = float(swing)
    atr   = float(atr)

    if direction == 'long':
        sl = swing - atr
        tp = entry + (2 * atr)
    elif direction == 'short':
        sl = swing + atr
        tp = entry - (2 * atr)

    print("For {0} on an entry of {1}, SL={2} and TP={3}".format(
        direction, entry, sl, tp))

if __name__ == '__main__':
    argh.dispatch_command(main)

但想使用 Elm 为它创建一个 Web UI。

4

1 回答 1

2

这不是对 Elm 的理想首次介绍,因为它将带您了解 Elm 的一些更困难的领域:邮箱和 Graphics.Input 库。也没有一个易于部署的数字输入,所以我只实现了下拉;你会使用Graphics.Input.Field(这可能会变得特别危险)。

邮箱基本上是下拉输入可以向其发送消息的信号。我选择将该消息作为一个函数,特别是如何从旧状态生成新状态。我们将状态定义为记录类型(如 Python 命名的元组),因此保存方向涉及将新方向存储在记录中。

文本是使用一个方便的函数来呈现的monospace。你可以使用一个完整的文本库,但是 Elm 0.15 没有字符串插值,所以你被非常丑陋的附加所困。

最后,关于 SO 的 Elm 社区并不多,但欢迎您加入邮件列表,欢迎此类问题。话虽如此,您确实应该尝试深入 Elm 并学习基础知识,以便您可以提出更具体的问题。几乎任何语言、库或框架都是如此——在编写“有用的”代码之前,您必须进行一些基本练习。

import Graphics.Input as Input
import Graphics.Element as Element exposing (Element)

mailbox = Signal.mailbox identity

type Direction = Short | Long
type alias State = {entry : Float, swing : Float, atr : Float, dir : Direction}

initialState : State
initialState = State 0 0 0 Short

dropdown : Element
dropdown =
    Input.dropDown
    (\dir -> Signal.message mailbox.address (\state -> {state| dir <- dir}))
    [("Short", Short), ("Long", Long)]

state : Signal State
state = Signal.foldp (<|) initialState mailbox.signal

render : State -> Element
render state =
    dropdown `Element.above`
    Element.show ("For "++(toString state.dir)++" on an entry of "++(toString state.entry) ++
                  ", SL="++(toString (sl state))++" and TP="++(toString (tp state)))

main = Signal.map render state

-- the good news: these are separate, pure functions
sl {entry, swing, atr, dir} =
    case dir of
        Long -> swing - atr
        Short -> swing + atr

tp {entry, swing, atr, dir} =
    case dir of
        Long -> entry + (2*atr)
        Short -> entry - (2*atr)

更新:我写了一篇关于邮箱以及如何使用它们的文章。

于 2015-07-06T20:44:23.870 回答