Elm – Commands ”; Previous Next In the previous chapters, we discussed the various components of Elm architecture and their functions. The user and the application communicate with one another using Messages. Consider an example, where the application needs to communicate with other components like an external server, APIs, microservice, etc. to serve the user request. This can be achieved by using Commands in Elm. Messages and commands are not synonymous. Messages represent the communication between an end user and the application while commands represent how an Elm application communicates with other entities. A command is triggered in response to a message. The following figure shows the workflow of a complex Elm application − The user interacts with the view. The view generates an appropriate message based on the user”s action. The update component receives this message and triggers a command. Syntax The syntax for defining a command is as given below − type Cmd msg The message generated by the view is passed to the command. Illustration The following example makes a request to an API and displays the result from the API. The application accepts a number from the user, passes it to the Numbers API. This API returns facts related to the number. The various components of the application are as follows − Http Module The Http Module of Elm is used to create and send HTTP requests. This module is not a part of the core module. We will use the elm package manager to install this package. API In this example, the application will communicate with the Numbers API – “http://numbersapi.com/#42“. View The application”s view contains a textbox and a button. view : Model -> Html Msg view model = div [] [ h2 [] [text model.heading] ,input [onInput Input, value model.input] [] , button [ onClick ShowFacts ] [ text “show facts” ] , br [] [] , h3 [][text model.factText] ] Model The Model represents the value entered by the user and the result that will be returned by the API. type alias Model = { heading : String , factText : String , input :String } Message The application has the following three messages − ShowFacts Input NewFactArrived Upon clicking the Show Facts button, ShowFacts message is passed to the update method. When the user types some value in the textbox, the Input message is passed to update method. Finally, when the Http server response is received, the NewFactArrived message will be passed to update. type Msg = ShowFacts |Input String | NewFactArrived (Result Http.Error String) Update The update method returns a tuple, which contains the model and command objects. When the user clicks on the Show Facts button, the Message is passed to the update which then calls the NumbersAPI. update : Msg -> Model -> (Model, Cmd Msg) update msg model = case msg of Input newInput -> (Model “NumbersApi typing..” “” newInput ,Cmd.none) ShowFacts -> (model, getRadmonNumberFromAPI model.input) NewFactArrived (Ok newFact) -> (Model “DataArrived” newFact “”, Cmd.none) NewFactArrived (Err _) -> (model, Cmd.none) Helper Function The helper function getRandomNumberFromAPI invokes the NumbersAPI and passes to it the number entered by the user. The result returned by the API is used to update the model. getRadmonNumberFromAPI : String->Cmd Msg getRadmonNumberFromAPI newNo = let url = “http://numbersapi.com/”++newNo in Http.send NewFactArrived (Http.getString url) Sr. No. Method Signature Description 1 Http.getString getString : String -> Request String Create a GET request and interpret the response body as a String. 2 Http.send send:(Result Error a -> msg) -> Request a -> Cmd msg Send a Http request. main This is the entry point of the Elm project. main = Html.program { init = init , view = view , update = update , subscriptions = subscriptions } Putting it all together Step 1 − Create folder CommandApp and file CommandDemo.elm. Step 2 − Install http module using command elm package install elm-lang/http. Step 2 − Type the contents for CommandDemo.elm as shown below − import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (..) import Http main = Html.program { init = init , view = view , update = update , subscriptions = subscriptions } — MODEL type alias Model = { heading : String , factText : String , input :String } init : (Model, Cmd Msg) init = ( Model “NumbersAPI” “NoFacts” “42”– set model two fields , Cmd.none — not to invoke api initially ) — UPDATE type Msg = ShowFacts |Input String | NewFactArrived (Result Http.Error String) update : Msg -> Model -> (Model, Cmd Msg) update msg model = case msg of Input newInput -> (Model “NumbersApi typing..” “” newInput ,Cmd.none) ShowFacts -> (model, getRadmonNumberFromAPI model.input) NewFactArrived (Ok newFact) -> (Model “DataArrived” newFact “”, Cmd.none) NewFactArrived (Err _) -> (model, Cmd.none) – VIEW view : Model -> Html Msg view model = div [] [ h2 [] [text model.heading] ,input [onInput Input, value model.input] [] , button [ onClick ShowFacts ] [ text “show facts” ] , br [] [] , h3 [][text model.factText] ] — SUBSCRIPTIONS subscriptions : Model -> Sub Msg subscriptions model = Sub.none — HTTP getRadmonNumberFromAPI : String->Cmd Msg getRadmonNumberFromAPI newNo = let url = “http://numbersapi.com/”++newNo in Http.send NewFactArrived (Http.getString url) Step 4 − Fire the command. C:UsersdellelmCommandApp> elm make .CommandDemo.elm This will generate the html file as shown below. Print Page Previous Next Advertisements ”;
Category: elm
ELM – Home
Elm Tutorial PDF Version Quick Guide Resources Job Search Discussion Elm is a pure functional programming language that compiles to JavaScript. It simplifies the language as well as an application framework. Elm is designed specifically for web frontend with the unique feature of no Runtime exceptions. This tutorial adopts a simple and practical approach to describe the concepts of Elm programming. Audience This tutorial has been prepared for beginners to help them understand the basic and advanced concepts of Elm. Prerequisites An understanding of basic programming concepts is necessary for this course. Print Page Previous Next Advertisements ”;
ELM – List
Elm – List ”; Previous Next The List, Tuples and Record data structures can be used to store a collection of values. This chapter discusses how to use List in Elm. A List is a collection of homogeneous values. The values in a list must all be of the same data type. Consider the following limitations while using variables to store values − Variables are scalar in nature. In other words, at the time of declaration a variable can hold only one value. This means that to store n values in a program, n variable declarations will be needed. Hence, the use of variables is not feasible when one needs to store a larger collection of values. Variables in a program are allocated memory in random order, thereby making it difficult to retrieve/read the values in the order of their declaration. Syntax List_name = [value1,value2,value3…..valuen] Illustration The following example shows how to use a List in Elm. Try this example in elm REPL − > myList1 = [10,20,30] [10,20,30] : List number > myList2 = [“hello”,”world”] [“hello”,”world”] : List String If we try adding values of different types into a list, the compiler will throw a type mismatch error. This is shown below. > myList = [1,”hello”] — TYPE MISMATCH ——————————————— repl-temp-000.elm The 1st and 2nd entries in this list are different types of values. 4| [1,”hello”] ^^^^^^^ The 1st entry has this type: number But the 2nd is: String List operations Following table shows the common operations on a List − Sr. No Method Description 1 isEmpty : List a -> Bool checks if list is empty 2 reverse : List a -> Bool reverses input list 3 length : List a -> Int returns size of the list 4 maximum : List comparable -> Maybe.Maybe comparable returns maximum value 5 minimum : List comparable -> Maybe.Maybe comparable returns minimum value 6 sum : List number -> number returns sum of all elements in list 7 product : List number -> number checks if list is empty 8 sort : List comparable -> List comparable sorts list in ascending order 9 concat : List (List a) -> List a merges a bunch of list into one 10 append : List a -> List a -> List a merges two lists together 11 range : Int -> Int -> List Int returns a list of numbers from start to end 12 filter : (a -> Bool) -> List a -> List a filters list of values from input list 13 head : List a -> Maybe.Maybe a returns the first element from list 14 tail : : List a -> Maybe.Maybe (List a) returns all elements except the head isEmpty This function returns true if a list is empty. Syntax List.isEmpty list_name To check the signature of function, type the following in elm REPL − > List.isEmpty <function> : List a -> Bool Illustration > List.isEmpty <function> : List a -> Bool > List.isEmpty [10,20,30] False : Bool reverse This function reverses the list. Syntax List.reverse list_name To check the signature of function, type the following in elm REPL − > List.reverse <function> : List a -> List a Illustration > List.reverse [10,20,30] [30,20,10] : List number length This function returns the length of a list. Syntax List.length list_name To check the signature of function, type the following in elm REPL − > List.length <function> : List a -> Int Illustration > List.length [10,20,30] 3 : Int maximum This function returns the maximum element in a non-empty list. Syntax List.maximum list_name To check the signature of function, type the following in elm REPL − > List.maximum <function> : List comparable -> Maybe.Maybe comparable Illustration > List.maximum [10,20,30] Just 30 : Maybe.Maybe number > List.maximum [] Nothing : Maybe.Maybe comparable minimum This function returns the minimum element in a non-empty list. Syntax List.minimum list_name To check the signature of function, type the following in elm REPL − > List.minimum <function> : List comparable -> Maybe.Maybe comparable Illustration > List.minimum [10,20,30] Just 10 : Maybe.Maybe number sum This function returns the sum of all elements in a list. Syntax List.sum list_name To check the signature of function, type the following in elm REPL − > List.sum <function> : List number -> number Illustration > List.sum [10,20,30] 60 : number product This function returns the product of all elements in a list. Syntax List.product list_name To check the signature of function, type the following in elm REPL − <function> : List number -> number Illustration List.product [10,20,30] 6000 : number sort This function sorts values from lowest to highest in a list. Syntax List.sort list_name To check the signature of function, type the following in elm REPL − > List.sort <function> : List comparable -> List comparable Illustration > List.sort [10,20,30] [10,20,30] : List number concat This function concatenates a bunch of lists into a single list. Syntax List.concat [ [list_name1],[list_name2],[list_name3],…..[list_nameN] ] To check the signature of function, type the following in elm REPL − > List.concat <function> : List (List a) -> List a Illustration > List.concat [[10,20], [30,40],[50,60]] [10,20,30,40,50,60] : List number append This function puts two lists together. Syntax List.append [list_name1] [list_name2] To check the signature of function, type the following in elm REPL − > List.append <function> : List a -> List a -> List a Illustration > List.append [10,20] [30,40] [10,20,30,40] : List number The ++ operator can also be used to append a list to another. This is shown in the example below − > [10.1,20.2] ++ [30.3,40.4] [10.1,20.2,30.3,40.4] : List Float range This function creates a list of numbers, every element increasing by one. The lowest and the highest number that should be in the list is passed to the function. Syntax List.range start_range end_range To check the signature of function, type the following in elm REPL − > List.range <function> : Int -> Int -> List Int Illustration > List.range 1 10 [1,2,3,4,5,6,7,8,9,10] : List Int filter This function filters a
ELM – Quick Guide
Elm – Quick Guide ”; Previous Next Elm – Introduction Elm is a functional programming language. It was Designed by Evan Czaplicki in 2012. Elm is specifically used for designing front end of web applications. Elm compiles to JavaScript and runs in the browser. It is fast, testable, maintainable, and comes with no Runtime exceptions. Some practical applications of the Elm programming platform include − Games Graphics Single Page Applications Why Elm Elm eliminates most of the common problems faced by frontend developers. This includes − No Runtime Exceptions Elm is a statically typed language. All possible errors are validated and corrected at compile-time. This makes it possible to have no runtime exceptions. Developer Friendly Error Messages Unlike other programming languages, Elm”s compiler is designed to provide very specific and developer-friendly error messages at compile time. The error messages also include hints such as links to recommended design documentations. Easy to Test Each Elm function can be tested in isolation of all others. This makes programs written in Elm easily testable. Automatic Semantic Versioning Elm enforces automatic semantic versioning of packages. This ensures that a patch change does not crash an already running application. Reusable Code Elm functions are inherently easy to reuse compared to functions in JavaScript, Python, or TypeScript. Elm – Environment Setup This chapter discusses steps to install Elm on Windows, Mac and Linux platforms. Local Environment Setup Consider the steps shown below to install Elm in your local environment. Step 1 − Install node Since elm is compiled to JavaScript, the target machine should have node installed. Refer to TutorialsPoint NodeJS course for steps to setup node and npm Node setup. Step 2 − Install elm Execute the following command on the terminal to install elm. Note that the stable version of elm was 0.18 at the time of writing this course. npm install -g [email protected] After installation, execute the following command to verify the version of Elm. C:Usersdell>elm –version 0.18.0 Step 2 − Install the Editor The development environment used here is Visual Studio Code (Windows platform). Visual Studio Code is an open source IDE from Visual Studio. It is available for Mac OS X, Linux and Windows platforms. VSCode is available at https://code.visualstudio.com/. Installation on Windows In this section, we will discuss the steps to install Elm on Windows. Download https://code.visualstudio.com/. for Windows. Double-click on VSCodeSetup.exe to launch the setup process. This will only take a minute. You may directly traverse to the file’s path by right clicking on File → Open in command prompt. Similarly, the Reveal in Explorer option shows the file in the File Explorer. Installation on Mac OS X Visual Studio Code’s Mac OS X specific installation guide can be found at VSCode Installation-MAC. Installation on Linux Visual Studio Code’s Linux specific installation guide can be found at VSCode Installation-Linux. Step 4 − Install the elm Extension Install the elm extension in VSCode as shown below. Elm REPL REPL stands for Read Eval Print Loop. It represents a computer environment like a Windows console or Unix/Linux shell where a command is entered and the system responds with an output in an interactive mode. Elm comes bundled with a REPL environment. It performs the following tasks − Read − Reads user”s input, parses the input into elm data-structure, and stores in memory. Eval − Takes and evaluates the data structure. Print − Prints the result. Loop − Loops the above command until the user exits. Use the command :exit to exit REPL and return to the terminal. A simple example to add two numbers in REPL is shown below − Open the VSCode terminal and type the command elm REPL. The REPL terminal waits for the user to enter some input. Enter the following expression 10 + 20. The REPL environment processes the input as given below − Reads numbers 10 and 20 from user. Evaluates using the + operator. Prints result as 30. Loops for next user input. Here we exit from loop. Elm – Basic Syntax This chapter discusses how to write a simple program in elm. Step 1 − Create a directory HelloApp in VSCode Now, create a file − Hello.elm in this directory. The above diagram shows project folder HelloApp and terminal opened in VSCode. Step 2 − Install the necessary elm packages The package manager in elm is elm-package. Install the elm-lang/html package. This package will help us display output of elm code in the browser. Traverse to the HelloApp project folder by right clicking on File → Open in command prompt in VSCode. Execute the following command in the terminal window − C:UsersdellElmHelloApp> elm-package install elm-lang/html The following files/folders are added to the project directory on installing the package. elm-package.json (file), stores project meta data elm-stuff (folder), stores external packages The following message will appear once the package is installed successfully. Step 3 − Add the following code to the Hello.elm file — importing Html module and the function text import Html exposing (text) — create main method main = — invoke text function text “Hello Elm from TutorialsPoint” The above program will display a string message Hello Elm from TutorialsPoint in the browser. For this, we need to import the function text within the Html module. The text function is used to print any string value in the browser. The main method is the entry point to a program. The main method invokes the text function and passes a string value to it. Step 4 − Compile the project Execute the following command in VSCode terminal window. elm make Hello.elm The output of the above command is as shown below − //update path to the proj folder in the command elm make C:UsersdellelmHelloApp>elm make Hello.elm Success! Compiled 38 modules. Successfully generated index.html The above command will generate an index.html file. The elm compiler converts .elm file to JavaScript and embeds it in the index.html file. Step 5 − Open the index.html in the browser Open the index.html file in any
ELM – Decision Making
Elm – Decision Making ”; Previous Next Decision-making structures requires that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Shown below is the general form of a typical decision-making structure found in most of the programming languages A decision-making construct evaluates a condition before the instructions are executed. Decision-making constructs in Elm are classified as follows − Sr. No. Statement Description 1 if…then…else statement The if statement consists of a Boolean expression followed by then which is executed if the expression returns true and else which is executed if the expression returns false 2 nested if statement You can use one if…then…else inside another if. 3 case statement Tests the value of a variable against a list of values. if…then…else Statement The if…then construct evaluates a condition before a block of code is executed. If the Boolean expression evaluates to true, then the block of code inside the then statement will be executed. If the Boolean expression evaluates to false, then the block of code inside the else statement will be executed. Unlike other programming languages, in Elm we must provide the else branch. Otherwise, Elm will throw an error. Syntax if boolean_expression then statement1_ifTrue else statement2_ifFalse Illustration Try the following example in the REPL terminal. > if 10>5 then “10 is bigger” else “10 is small” “10 is bigger” : String Nested If The nested if statement is useful for testing multiple conditions. The syntax of a nested if statement is given below − if boolean_expression1 then statement1_ifTrue else if boolean_expression2 then statement2_ifTrue else statement3_ifFalse Illustration Try the following example in the Elm REPL − > score=80 80 : number > if score>=80 then “Outstanding” else if score > = 70 then “good” else “average” “Outstanding” : String Case statement The case statement can be used to simplify the if then else statement. The syntax of a case statement is as given below − case variable_name of constant1 -> Return_some_value constant2 -> Return_some_value _ -> Return_some_value if none of the above values match The case statement checks if the value of a variable matches a predefined set of constants and returns the corresponding value. Note that value returned by each case must be of the same type. If the variables value does not match any of the given constants, the control is passed to * default * (denoted by //_ ) and the corresponding value is returned. Illustration Try the following example in the Elm REPL − > n = 10 10 : number > case n of | 0 -> “n is Zero” | _ -> “n is not Zero” “n is not Zero” : String The above code snippet checks if the value of n is zero. The control is passed to default, which returns the string “n is not Zero”. Print Page Previous Next Advertisements ”;
ELM – Tuples
Elm – Tuples ”; Previous Next At times, there might be a need to store a collection of values of varied types. Elm gives us a data structure called tuple that serves this purpose. A tuple represents a heterogeneous collection of values. In other words, tuples enable storing multiple fields of different types. A tuple stores fixed number of values. Tuples are useful when you want to return multiple values of different types from a function. These data structures are immutable like other types in elm. Syntax (data1,data2) A simple example is shown below − > (“TuotrialsPoint”,5,True,”Hyderabad”) (“TuotrialsPoint”,5,True,”Hyderabad”) : ( String, number, Bool, String ) In our subsequent sections, we will learn about the different tuple operations. first This operation extracts the first value from a tuple. Syntax Tuple.first tuple_name > Tuple.first <function> : ( a1, a2 ) -> a1 Illustration > Tuple.first (10,”hello”) 10 : number second The second tuple operation extracts the second value from a tuple. Syntax Tuple.second tuple_name > Tuple.second <function> : ( a1, a2 ) -> a2 Illustration > Tuple.second (10,”hello”) “hello” : String List of tuples A List can store Tuples. If tuples are used inside a list, make sure they all are of the same data type and have the same number of parameters. Illustration > [(“hello”,20),(“world”,30)] [(“hello”,20),(“world”,30)] : List ( String, number ) Tuple with function A function can return tuples. In addition, tuples can be passed as parameters to functions. Illustration 1 The following example defines a function fn_checkEven. This function accepts an integer value as parameter and returns a tuple. > fn_checkEven no = if no%2 == 0 then (True,”The no is Even”) else (False,”No is not even”) <function> : Int -> ( Bool, String ) > fn_checkEven 10 (True,”The no is Even”) : ( Bool, String ) > fn_checkEven 11 (False,”No is not even”) : ( Bool, String ) > Illustration 2 The following passes a tuple as a parameter to a function. > fn_add (a,b) = | a+b <function> : ( number, number ) -> number > fn_add (10,20) 30 : number The function fn_add takes a tuple with 2 numeric values and returns their sum. Destructuring Destructuring involves breaking a tuple into individual values. To access individual values in a tuple with three or more elements, we use destructuring. Here, we assign each value in a tuple to different variables. Using _ one can define placeholders for values that will be ignored or skipped. Illustration > (first,_,_) = (10,20,30) 10 : number > first 10 : number Illustration In this example, we wil use let..in block syntax to destructure. The let block contains the variables and the in block contains expressions that should be evaluated and value that should be returned. > t1 = (10,20,30) (10,20,30) : ( number, number1, number2 ) > let (a,b,c) = t1 in a + b +c 60 : number We are declaring variables a b c in let clause and accessing them using in clause. Print Page Previous Next Advertisements ”;
ELM – Useful Resources
Elm – Useful Resources ”; Previous Next The following resources contain additional information on Elm. Please use them to get more in-depth knowledge on this. Useful Links on Elm Elm − Official site of Elm. Elm @ Wikipedia − Elm, its history and various other terms has been explained in simple language. Useful Books on Elm To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;
ELM – Records
Elm – Records ”; Previous Next The record data structure in Elm can be used to represent data as key-value pairs. A record can be used to organize related data to enable easy access and updating data. Elm records are similar to objects in JavaScript. Data elements in a record are known as fields. Defining a Record Use the following syntax to define a record − Syntax record_name = {fieldname1 = value1, fieldname2 = value2….fieldnameN = valueN} A record can store data of multiple types. The field names in a record must conform to the general rules for naming an Elm identifier. Accessing record values Use the following syntax to access individual fields in a record. Syntax record_name.fieldname OR .fieldname record_name Illustration Try the following in the Elm REPL − > company = {name=”TutorialsPoint”,rating=4.5} { name = “TutorialsPoint”, rating = 4.5 } : { name : String, rating : Float } > company.name “TutorialsPoint” : String > .rating company 4.5 : Float Using Record with List A record can be stored inside a list. All field values of the record should be of the same type. Syntax list_name = [ {field_name1 = value1},{field_name1 = value2}] OR list_name = [record_name1, record_name2, record_name3….record_nameN] Illustration Try the following in Elm REPL − > [{name = “Mohtashim”},{name = “kannan”}] [{ name = “Mohtashim” },{ name = “kannan” }] : List { name : String } > record1 = {name = “FirstRecord”} { name = “FirstRecord” } : { name : String } > record2 = {name = “SecondRecord”} { name = “SecondRecord” } : { name : String } > recordList = [record1,record2] [{ name = “FirstRecord” },{ name = “SecondRecord” }] : List { name : String } Update a Record Records are immutable in Elm. When a record is updated, a new record with updated values is returned. The field can hold value of a different type when updating a record. Syntax {record_name | field_name1 = new_value1, field_name2 = new_value2,field_name3 = new_value3….field_nameN = new_valueN} Illustration Try the following in Elm REPL − > record1 = {name=”FirstRecord”} { name = “FirstRecord” } : { name : String } > record1_updated = {record1 | name = “FirstRecordUpdate”} { name = “FirstRecordUpdate” } : { name : String } > record1 { name = “FirstRecord” } : { name : String } > record1 == record1_updated False : Bool Illustration The following example updates multiple fields of a record. Try the following in Elm REPL − > record3 = {a = 1,b = 2,c = 3,d = 4,e = 5} { a = 1, b = 2, c = 3, d = 4, e = 5 } : { a : number, b : number1, c : number2, d : number3, e : number4 } > record4 = {record3 | d=400 ,e=500} { a = 1, b = 2, c = 3, d = 400, e = 500 } : { a : number2, b : number3, c : number4, d : number, e : number1 } > Types alias Type alias defines a schema for a record. In other words, a type alias defines which fields can the record store and the type of value these fields can store. Therefore, programmer will not make mistake of missing any specific attribute while assigning values. Syntax type alias alias_name = {field_name1:data_type,field_name2:data_type,….field_nameN:data_type} Illustration Execute the following in Elm REPL − > type alias Developer = { name:String,location:String,age:Int} > dev1 = Developer “kannan” “Mumbai” 20 { name = “kannan”, location = “Mumbai”, age = 20 } : Repl.Developer > dev2 = Developer “mohtashim” “hyderabad” 20 { name = “mohtashim”, location = “hyderabad”, age = 20 } : Repl.Developer > Now if you forget to type location and age, the statement returns a function, which has input parameters for location and age fields. > dev3 = Developer “Bhagavati” <function> : String -> Int -> Repl.Developer We can invoke the function as shown below and pass to it the values for location and age fields. > dev3 “Pune” 25 { name = “Bhagavati”, location = “Pune”, age = 25 } : Repl.Developer Print Page Previous Next Advertisements ”;
ELM – Functions
Elm – Functions ”; Previous Next Functions are the building blocks of an Elm program. A function is a set of statements to perform a specific task. Functions organize the program into logical blocks of code. Once defined, functions may be called to access code. This makes the code reusable. Moreover, functions make it easy to read and maintain the program’s code. Steps to using a function There are three steps to using a function − Function Declaration A function declaration tells the compiler about a function”s name, return type, and parameters. The syntax for declaring a function is given below − fn_name:data_type_of_the_parameters ->return_type The function declaration specifies the following − Name of the function. Data type of the parameters. This is optional as a function may or may not have parameters. Data type of the value, which the function will return. Functions in Elm must always return a value as Elm is a functional programming language. Unlike functions in other programing languages, Elm functions do not use the return keyword to return a value. Function Definition or Function Implementation A function definition provides the actual body of the function. A function definition specifies how a specific task would be done. The syntax for defining a function is as given below − fn_name parameter1 parameter2 = statements Invoking or Calling a Function A function must be called so as to execute it. The syntax for calling a function is given below − fn_name parameter1 parameter2 Illustration The following code defines a function greet. The function returns a string “Hello”. > greet = | if True then | “Hello” | else | “GoodBye” “Hello” : String > greet “Hello” : String Parameterized Functions Parameters are a mechanism to pass values to a function. The values of the parameters are passed to the function at the time of function invocation. Illustration 1 The following example defines a function fn_add. The function accepts two numbers as parameters and returns their sum. Try the following in elm REPL − > fn_add x y = x+y <function> : number -> number -> number > fn_add 10 20 30 : number Illustration 2 The following example defines a function sayHello. The sayHello function accepts and returns a String value as parameter and returns a String. > sayHello name = “Hello “++ name <function> : String -> String > sayHello “Tutorialspoint” “Hello Tutorialspoint” : String > Pipe Operator To understand pipe operator |>, let us consider an example where we have a list of different strings [“a”,”b”,”c”] . Now we need a single string, which is separated by − The following example shows how to do that with String.join > String.join “-” [“a”,”b”,”c”,”d”,”e”,”f”] “a-b-c-d-e-f” : String The same action can be performed by using a pipe operator |>. The pipe operator can be used to chain multiple function calls. > [“a”,”b”,”c”,”d”,”e”,”f”] |> String.join “-” “a-b-c-d-e-f” : String > [“a”,”b”,”c”,”d”,”e”,”f”] |> List.reverse |> String.join “-” “f-e-d-c-b-a” : String In the first example, we are chaining the list to join method. In the second case, the same list is piped to reverse function and thereafter piped to join. So, the list is displayed in reversed and joined. Print Page Previous Next Advertisements ”;
ELM – Subscriptions
Elm – Subscriptions ”; Previous Next In the previous chapter, we discussed that a View interacts with other components using Commands. Similarly, a component (E.g. WebSocket) can talk to a View using Subscriptions. Subscriptions are a way that an Elm application can receive external inputs like keyboard events, timer events and WebSocket events. The following figure explains the role of Subscriptions in an Elm application. The user interacts with an Elm application via messages. The application given uses WebSocket and it has two modes of operations − Send client-side data to socket server via Command Receive data anytime from the socket server via Subscription Syntax The syntax for defining a subscription is given below − type Sub msg Illustration Let us understand subscriptions using a simple example. In the example given below, the application sends a message to the server. The server is an echo server, which responds to the client with the same message. All the incoming messages are later displayed in a list. We will use WebSocket (wss protocol) to be able to continuously listen for messages from the server. The WebSocket will send user input to the server using Commands while it will use Subscription to receive messages from the server. The various components of the application are given below − Echo server The echo server can be accessed using the wss protocol. The echo server sends back user input to the application. The code for defining an echo server is given below − echoServer : String echoServer = “wss://echo.websocket.org” Model The Model represents user input and a list of incoming messages from the socket server. The code for defining the Model is as given below − type alias Model = { input : String , messages : List String } Messages The message type will contain Input for taking text input from user. The Send message will be generated when user clicks the button to send message to WebSocket server. The NewMessage is used when message arrives from echo server. type Msg = Input String | Send | NewMessage String View The application”s view contains a textbox and a submit button to send user input to the server. The response from the server is displayed on the View using a div tag. view : Model -> Html Msg view model = div [] [ input [onInput Input, value model.input] [] , button [onClick Send] [text “Send”] , div [] (List.map viewMessage (List.reverse model.messages)) ] viewMessage : String -> Html msg viewMessage msg = div [] [ text msg ] Update The update function takes the message and the model components. It updates the model based on the message type. update : Msg -> Model -> (Model, Cmd Msg) update msg {input, messages} = case msg of Input newInput -> (Model newInput messages, Cmd.none) Send -> (Model “” messages, WebSocket.send echoServer input) NewMessage str -> (Model input (str :: messages), Cmd.none) Sr. No. Method Signature Description 1 WebSocket.listen listen : String -> (String -> msg) -> Sub msg Subscribes to any incoming messages on a websocket. 2 WebSocket.send send : String -> String -> Cmd msg Sends a wss request to a server address. It is important that you are also subscribed to this address with listen. If you are not, the web socket will be created to send one message and then closed. Subscription The subscription function takes in the model object. To receive the messages from WebSocket server, we call WebSocket.listen passing in the message as NewMessage. When a new message comes from the server, the update method is called. subscriptions : Model -> Sub Msg subscriptions model = WebSocket.listen echoServer NewMessage main The main function is the entry point to the elm application as shown below. main = Html.program { init = init , view = view , update = update , subscriptions = subscriptions } Putting it all together Step 1 − Create a directory,SubscriptionApp and add a file,SubscriptionDemo.elm to it. Step 2 − Add the following contents to SubscriptionDemo.elm file − import Html exposing (..) import Html.Attributes exposing (..) import Html.Events exposing (..) import WebSocket main = Html.program { init = init , view = view , update = update , subscriptions = subscriptions } echoServer : String echoServer = “wss://echo.websocket.org” — MODEL type alias Model = { input : String , messages : List String } init : (Model, Cmd Msg) init = (Model “” [], Cmd.none) — UPDATE type Msg = Input String | Send | NewMessage String update : Msg -> Model -> (Model, Cmd Msg) update msg {input, messages} = case msg of Input newInput -> (Model newInput messages, Cmd.none) Send -> (Model “” messages, WebSocket.send echoServer input) NewMessage str -> (Model input (str :: messages), Cmd.none) — SUBSCRIPTIONS subscriptions : Model -> Sub Msg subscriptions model = WebSocket.listen echoServer NewMessage — VIEW view : Model -> Html Msg view model = div [] [ input [onInput Input, value model.input] [] , button [onClick Send] [text “Send”] , div [] (List.map viewMessage (List.reverse model.messages)) ] viewMessage : String -> Html msg viewMessage msg = div [] [ text msg ] Step 3 − Install the websockets package using elm package manager. C:UsersdellelmSubscriptionApp> elm-package install elm-lang/websocket Step 4 − Build and generate index.html file as shown below. C:UsersdellelmSubscriptionApp> elm make .SubscriptionDemo.elm Step 5 − Upon execution, the following output will be generated − Print Page Previous Next Advertisements ”;