Showing posts with label Elm. Show all posts
Showing posts with label Elm. Show all posts

Monday, December 07, 2015

LED es mi nuevo Hello World - Tiempo de Elm

Así que...como lo prometí...aquí está mi aplicación de Números LED escrita en Elm -:)

Ahora...esto me tomó más tiempo del esperado, por un par de detalle...

a) A Elm le gusta manejar valores Just y Maybe...Haskell también lo hace...pero Haskell provee funciones alternativas que manejan el Just y el Maybe...Elm no...así que tuve que crear algunas funciones adicionales para manejarlo...

b) Elm no provee una funcion para obtener elementos de una lista...así que tuve que crear la función...

c) Todavía soy un novato en Elm

Poniéndo eso de lado...Elm sigue siendo asombroso y me encanta -;)

En fín...hay que ponernos a trabajar...

Debemos crear una carpeta llamada LED_Numbers y escribir esto en el terminal...

elm package install evancz/elm-html

elm package install evancz/start-app

Luego, abre tu editor favorito y copia y pega este código...

LED_Numbers.elm
module LED_Numbers where

import Html exposing (..)
import Html.Events exposing (..)
import Html.Attributes exposing (..)
import StartApp.Simple as StartApp
import String exposing (toInt,toList)
import Dict

--MODEL
type alias Model =
  { 
    number: String,
    leds: Dict.Dict Char (List String),
    line: String
  }

initialModel: Model
initialModel = 
  {
    number = "",
    leds = Dict.fromList[('0',[" _  ","| | ","|_| "]),('1',["  ","| ","| "]),
                         ('2',[" _  "," _| ","|_  "]),('3',["_  ","_| ","_| "]),
                         ('4',["    ","|_| ","  | "]),('5',[" _  ","|_  "," _| "]),
                         ('6',[" _  ","|_  ","|_| "]),('7',["_   "," |  "," |  "]),
                         ('8',[" _  ","|_| ","|_| "]),('9',[" _  ","|_| "," _| "])],
    line = ""
  }

--UPDATE
fromJust : Maybe a -> a
fromJust x = case x of
  Just y -> y
  Nothing -> Debug.crash ""

fromMaybe : Maybe (List String) -> List String
fromMaybe x = case x of
  Just y -> y
  Nothing -> Debug.crash ""

fromMaybeChar : Maybe Char -> Char
fromMaybeChar x = case x of
  Just y -> y
  Nothing -> Debug.crash ""

get_elem : List a -> Int -> Maybe a
get_elem lst n =
  List.head (List.drop n lst)

fromMaybeListChar : Maybe (List Char) -> List Char
fromMaybeListChar x = case x of
  Just y -> y
  Nothing -> Debug.crash ""

get_list: String -> List Char
get_list str =
  String.toList str

type Action = NoOp | Submit | UpdateNumber String

update: Action -> Model -> Model
update action model =
  case action of
    NoOp ->
      model
    UpdateNumber contents ->
      { model | number = contents }  
    Submit ->
      { model | 
          line = get_led (get_list model.number) 0 model,
          number = ""
      }

get_led: List Char -> Int -> Model -> String
get_led lst n model =
  if List.length lst > 0
  then let h = fromMaybeChar(List.head lst)
           t = fromMaybeListChar(List.tail lst)
           leds = model.leds
           line = Dict.get h leds
       in fromJust(get_elem (fromMaybe line) n) ++ get_led t n model
  else if n < 2
  then "" ++ "\n" ++ get_led (get_list model.number) (n+1) model
  else if n == 2
  then "" ++ "\n"
  else ""

--VIEW
buttonStyle: Attribute
buttonStyle = 
  style
    [ ("outline", "none"),
      ("border", "none"),
      ("border-radius","4px"),
      ("margin-right","5px"),
      ("padding","4px 10px"),
      ("background","#61a1bc"),
      ("color","#fff")
    ]

divStyle: Attribute
divStyle = 
  style
    [ ("margin", "50px auto"),
      ("padding", "0px 50px"),
      ("text-align", "center")
    ]

pStyle: Attribute
pStyle = 
  style
    [ ("font-size", "30px") ]

pageHeader : Html
pageHeader = 
  h1 [ ] [text "LED Numbers"]

view: Signal.Address Action -> Model -> Html
view address model = 
  div [ divStyle ]
    [ pageHeader,
      input
        [ 
          type' "text",
          name "number",
          placeholder "Enter a number",
          value model.number,
          on "input" targetValue (\v -> Signal.message address (UpdateNumber v))
        ]
        [ ],
      button [ buttonStyle, onClick address Submit ] [ text "Submit" ],
      pre [ pStyle ]
          [ text (model.line) ]
    ]
    
main: Signal Html
main = 
  StartApp.start { model = initialModel, view = view, update = update }

Anda al terminal y escribe esto...

elm make LED_Numbers.elm --output LED_Numbers.html

Abre el archivo en tu browser y ejecutalo...



Espero que les guste -;)

Saludos,

Blag.
Development Culture.

Thursday, December 03, 2015

Mi primer post en Elm

Mirándo en mi lista de nuevos lenguajes a aprender...me encontré con Elm...programación funcional y reactiva en el browser...


No es eso impresionante? Por supuesto que lo es -:)

Bueno...Elm comenzó a existir a mediados del 2012...así que es relativamente nuevo...lo cual significa que no hay muchos tutoriales y que yo sepa ningún libro...pero...no dejes que eso te asuste...existen un par de asombrosos cursos dictados por The Pragmatic Studio que te ayudarán a estar listo y preparado -;)

Elm: Building Reactive Web Apps

Elm: Signals, Mailboxes & Ports

Ahora...para instalar Elm...si ya tienes instalado NodeJS entonces simplemente puedes utilizar npm que es yo pienso la manera más rápida y sencilla...

sudo npm install elm

De lo contrario puedes ir a la sección de download para los instaladores o para el código fuente para compilarlo...pero debes tener en cuenta que para compilarlo vas a necesitar tener Haskell instalado también...

En todo caso...vamos a ver como crear una aplicación de List Fibonacci en Elm... -:)

Crea una carpeta y llamala "Fibonacci_App" y entra en la carpeta desde el terminal...

elm package install evancz/elm-html



elm package install evancz/start-app



El primer paquete nos va a permitir generar código HTML y el segundo va a hacer nuestras vidas más sencillas...

Ahora...abre tu editor favorito y copia y pega este código...

Fibonacci.elm
module Fibonacci where

import Html exposing (..)
import Html.Events exposing (..)
import Html.Attributes exposing (..)
import StartApp.Simple as StartApp
import String exposing (toInt)

--MODEL
type alias Model =
  { 
    number: String,
    fibonacci: String
  }

initialModel: Model
initialModel = 
  {
    number = "",
    fibonacci = ""
  }

--UPDATE
parseInt : String -> Int
parseInt string =
  case String.toInt string of
    Ok value ->
      value
    Err error ->
      0

type Action = NoOp | Submit | UpdateNumber String

update: Action -> Model -> Model
update action model =
  case action of
    NoOp ->
      model
    UpdateNumber contents ->
      { model | number = contents }  
    Submit ->
      { model | 
          fibonacci = fib (parseInt model.number) 0 1,
          number = ""
      }

fib: Int -> Int -> Int -> String
fib num a b =
  if a > 0 && num > 1 then toString(a+b) ++ " " ++ fib (num-1) (a+b) a
  else if a == 0 then toString a ++ " " ++ toString b ++ " " 
                      ++ toString(a+b) ++ " " ++ fib(num-1) (a+b) b
  else ""

--VIEW
buttonStyle: Attribute
buttonStyle = 
  style
    [ ("outline", "none"),
      ("border", "none"),
      ("border-radius","4px"),
      ("margin-right","5px"),
      ("padding","4px 10px"),
      ("background","#61a1bc"),
      ("color","#fff")
    ]

divStyle: Attribute
divStyle = 
  style
    [ ("margin", "50px auto"),
      ("padding", "0px 50px"),
      ("text-align", "center")
    ]

pStyle: Attribute
pStyle = 
  style
    [ ("font-size", "30px") ]

pageHeader : Html
pageHeader = 
  h1 [ ] [text "Fibonacci List"]

view: Signal.Address Action -> Model -> Html
view address model = 
  div [ divStyle ]
    [ pageHeader,
      input
        [ 
          type' "text",
          name "number",
          placeholder "Enter a number",
          value model.number,
          on "input" targetValue (\v -> Signal.message address (UpdateNumber v))
        ]
        [ ],
      button [ buttonStyle, onClick address Submit ] [ text "Submit" ],
      p [ pStyle ]
        [ text (model.fibonacci) ]
    ]
    
main: Signal Html
main = 
  StartApp.start { model = initialModel, view = view, update = update }

Luego, solo debemos compilar nuestra aplicación -;)

elm make Fibonacci.elm --output Fibonaccci.html



Ahora, podemos abrir el archivo Fibonacci.html y probar nuestra aplicación -:D



Espero que le haya gustado -:) Y voy a tratar de tener mi aplicación de Números LED terminada pronto -;)

Saludos,

Blag.
Development Culture.