使用 Elm 创建表单

Creating a form with Elm

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

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

我将其用作命令行 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 为它创建一个网站 UI。

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

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

文本是使用使它成为 monospace 的便捷函数呈现的。你可以使用整个 text library,但 Elm 0.15 没有字符串插值,所以你只能使用非常丑陋的附加。

最后,关于 SO 的 Elm 社区并不多,但欢迎您加入 mailing list,欢迎提出此类问题。话虽这么说,你真的应该尝试深入 Elm 并学习基础知识,这样你才能提出更具体的问题。几乎任何语言、库或框架都是如此——在编写 "useful" 代码之前,你必须做一些基本练习。

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)

更新:我写了 an essay 关于邮箱以及如何使用它们。