Haskell – Discussion

Discuss Haskell ”; Previous Next Haskell is a widely used purely functional language. Functional programming is based on mathematical functions. Besides Haskell, some of the other popular languages that follow Functional Programming paradigm include: Lisp, Python, Erlang, Racket, F#, Clojure, etc. Haskell is more intelligent than other popular programming languages such as Java, C, C++, PHP, etc. In this tutorial, we will discuss the fundamental concepts and functionalities of Haskell using relevant examples for easy understanding. Print Page Previous Next Advertisements ”;

Haskell – Decision Making

Haskell – Decision Making ”; Previous Next Decision Making is a feature that allows the programmers to apply a condition in the code flow. The programmer can execute a set of instructions depending on a predefined condition. The following flowchart shows the decision-making structure of Haskell − Haskell provides the following types of decision-making statements − Sr.No. Statement & Description 1 if–else statement One if statement with an else statement. The instruction in the else block will execute only when the given Boolean condition fails to satisfy. 2 Nested if-else statement Multiple if blocks followed by else blocks Print Page Previous Next Advertisements ”;

Haskell – Types and Type Class

Haskell – Types and Type Class ”; Previous Next Haskell is a functional language and it is strictly typed, which means the data type used in the entire application will be known to the compiler at compile time. Inbuilt Type Class In Haskell, every statement is considered as a mathematical expression and the category of this expression is called as a Type. You can say that “Type” is the data type of the expression used at compile time. To learn more about the Type, we will use the “:t” command. In a generic way, Type can be considered as a value, whereas Type Class can be the considered as a set of similar kind of Types. In this chapter, we will learn about different Inbuilt Types. Int Int is a type class representing the Integer types data. Every whole number within the range of 2147483647 to -2147483647 comes under the Int type class. In the following example, the function fType() will behave according to its type defined. Live Demo fType :: Int -> Int -> Int fType x y = x*x + y*y main = print (fType 2 4) Here, we have set the type of the function fType() as int. The function takes two int values and returns one int value. If you compile and execute this piece of code, then it will produce the following output − sh-4.3$ ghc -O2 –make *.hs -o main -threaded -rtsopts sh-4.3$ main 20 Integer Integer can be considered as a superset of Int. This value is not bounded by any number, hence an Integer can be of any length without any limitation. To see the basic difference between Int and Integer types, let us modify the above code as follows − Live Demo fType :: Int -> Int -> Int fType x y = x*x + y*y main = print (fType 212124454 44545454454554545445454544545) If you compile the above piece of code, the following error message will be thrown − main.hs:3:31: Warning: Literal 44545454454554545445454544545 is out of the Int range – 9223372036854775808..9223372036854775807 Linking main … This error occurred because our function fType() expecting one Int type value, and we are passing some real big Int type value. To avoid this error, Let us modify the type “Int” with “Integer” and observe the difference. Live Demo fType :: Integer -> Integer -> Integer fType x y = x*x + y*y main = print (fType 212124454 4454545445455454545445445454544545) Now, it will produce the following output − sh-4.3$ main 1984297512562793395882644631364297686099210302577374055141 Float Take a look at the following piece of code. It shows how Float type works in Haskell − Live Demo fType :: Float -> Float -> Float fType x y = x*x + y*y main = print (fType 2.5 3.8) The function takes two float values as the input and yields another float value as the output. When you compile and execute this code, it will produce the following output − sh-4.3$ main 20.689999 Double Double is a floating point number with double precision at the end. Take a look at the following example − Live Demo fType :: Double -> Double -> Double fType x y = x*x + y*y main = print (fType 2.56 3.81) When you execute the above piece of code, it will generate the following output − sh-4.3$ main 21.0697 Bool Bool is a Boolean Type. It can be either True or False. Execute the following code to understand how the Bool type works in Haskell − Live Demo main = do let x = True if x == False then putStrLn “X matches with Bool Type” else putStrLn “X is not a Bool Type” Here, we are defining a variable “x” as a Bool and comparing it with another Boolean value to check its originality. It will produce the following output − sh-4.3$ main X is not a Bool Type Char Char represent Characters. Anything within a single quote is considered as a Character. In the following code, we have modified our previous fType() function to accept Char value and return Char value as output. Live Demo fType :: Char-> Char fType x = ”K” main = do let x = ”v” print (fType x) The above piece of code will call fType() function with a char value of ”v” but it returns another char value, that is, ”K”. Here is its output − sh-4.3$ main ”K” Note that we are not going to use these types explicitly because Haskell is intelligent enough to catch the type before it is declared. In the subsequent chapters of this tutorial, we will see how different types and Type classes make Haskell a strongly typed language. EQ Type Class EQ type class is an interface which provides the functionality to test the equality of an expression. Any Type class that wants to check the equality of an expression should be a part of this EQ Type Class. All standard Type classes mentioned above is a part of this EQ class. Whenever we are checking any equality using any of the types mentioned above, we are actually making a call to EQ type class. In the following example, we are using the EQ Type internally using the “==” or “/=” operation. Live Demo main = do if 8 /= 8 then putStrLn “The values are Equal” else putStrLn “The values are not Equal” It will yield the following output − sh-4.3$ main The values are not Equal Ord Type Class Ord is another interface class which gives us the functionality of ordering. All the types that we have used so far are a part of this Ord interface. Like EQ interface, Ord interface can be called using “>”, “<“, “<=”, “>=”, “compare”. Please find below example where we used “compare ” functionality of this Type Class. Live Demo main = print (4 <= 2) Here, the Haskell compiler will check if 4 is less than or equal to 2. Since it is not, the code will produce the following output

Haskell – Monads

Haskell – Monads ”; Previous Next Monads are nothing but a type of Applicative Functor with some extra features. It is a Type class which governs three basic rules known as monadic rules. All the three rules are strictly applicable over a Monad declaration which is as follows − class Monad m where return :: a -> m a (>>=) :: m a -> (a -> m b) -> m b (>>) :: m a -> m b -> m b x >> y = x >>= _ -> y fail :: String -> m a fail msg = error msg The three basic laws that are applicable over a Monad declaration are − Left Identity Law − The return function does not change the value and it should not change anything in the Monad. It can be expressed as “return >=> mf = mf”. Right Identity Law − The return function does not change the value and it should not change anything in the Monad. It can be expressed as “mf >=> return = mf”. Associativity − According to this law, both Functors and Monad instance should work in the same manner. It can be mathematically expressed as “( f >==>g) >=> h =f >= >(g >=h)”. The first two laws iterate the same point, i.e., a return should have identity behavior on both sides of the bind operator. We have already used lots of Monads in our previous examples without realizing that they are Monad. Consider the following example where we are using a List Monad to generate a specific list. Live Demo main = do print([1..10] >>= (x -> if odd x then [x*2] else [])) This code will produce the following output − [2,6,10,14,18] Print Page Previous Next Advertisements ”;

Haskell – Functor

Haskell – Functor ”; Previous Next Functor in Haskell is a kind of functional representation of different Types which can be mapped over. It is a high level concept of implementing polymorphism. According to Haskell developers, all the Types such as List, Map, Tree, etc. are the instance of the Haskell Functor. A Functor is an inbuilt class with a function definition like − class Functor f where fmap :: (a -> b) -> f a -> f b By this definition, we can conclude that the Functor is a function which takes a function, say, fmap() and returns another function. In the above example, fmap() is a generalized representation of the function map(). In the following example, we will see how Haskell Functor works. Live Demo main = do print(map (subtract 1) [2,4,8,16]) print(fmap (subtract 1) [2,4,8,16]) Here, we have used both map() and fmap() over a list for a subtraction operation. You can observe that both the statements will yield the same result of a list containing the elements [1,3,7,15]. Both the functions called another function called subtract() to yield the result. [1,3,7,15] [1,3,7,15] Then, what is the difference between map and fmap? The difference lies in their usage. Functor enables us to implement some more functionalists in different data types, like “just” and “Nothing”. Live Demo main = do print (fmap (+7)(Just 10)) print (fmap (+7) Nothing) The above piece of code will yield the following output on the terminal − Just 17 Nothing Applicative Functor An Applicative Functor is a normal Functor with some extra features provided by the Applicative Type Class. Using Functor, we usually map an existing function with another function defined inside it. But there is no any way to map a function which is defined inside a Functor with another Functor. That is why we have another facility called Applicative Functor. This facility of mapping is implemented by Applicative Type class defined under the Control module. This class gives us only two methods to work with: one is pure and the other one is <*>. Following is the class definition of the Applicative Functor. class (Functor f) => Applicative f where pure :: a -> f a (<*>) :: f (a -> b) -> f a -> f b According to the implementation, we can map another Functor using two methods: “Pure” and “<*>”. The “Pure” method should take a value of any type and it will always return an Applicative Functor of that value. The following example shows how an Applicative Functor works − Live Demo import Control.Applicative f1:: Int -> Int -> Int f1 x y = 2*x+y main = do print(show $ f1 <$> (Just 1) <*> (Just 2) ) Here, we have implemented applicative functors in the function call of the function f1. Our program will yield the following output. “Just 4″ Monoids We all know Haskell defines everything in the form of functions. In functions, we have options to get our input as an output of the function. This is what a Monoid is. A Monoid is a set of functions and operators where the output is independent of its input. Let’s take a function (*) and an integer (1). Now, whatever may be the input, its output will remain the same number only. That is, if you multiply a number by 1, you will get the same number. Here is a Type Class definition of monoid. class Monoid m where mempty :: m mappend :: m -> m -> m mconcat :: [m] -> m mconcat = foldr mappend mempty Take a look at the following example to understand the use of Monoid in Haskell. Live Demo multi:: Int->Int multi x = x * 1 add :: Int->Int add x = x + 0 main = do print(multi 9) print (add 7) Our code will produce the following output − 9 7 Here, the function “multi” multiplies the input with “1”. Similarly, the function “add” adds the input with “0”. In the both the cases, the output will be same as the input. Hence, the functions {(*),1} and {(+),0} are the perfect examples of monoids. Print Page Previous Next Advertisements ”;

Haskell – Zippers

Haskell – Zippers ”; Previous Next Zippers in Haskell are basically pointers that point to some specific location of a data structure such as a tree. Let us consider a tree having 5 elements [45,7,55,120,56] which can be represented as a perfect binary tree. If I want to update the last element of this list, then I need to traverse through all the elements to reach at the last element before updating it. Right? But, what if we could construct our tree in such a manner that a tree of having N elements is a collection of [(N-1),N]. Then, we need not traverse through all the unwanted (N-1) elements. We can directly update the Nth element. This is exactly the concept of Zipper. It focuses or points to a specific location of a tree where we can update that value without traversing the entire tree. In the following example, we have implemented the concept of Zipper in a List. In the same way, one can implement Zipper in a tree or a file data structure. Live Demo data List a = Empty | Cons a (List a) deriving (Show, Read, Eq, Ord) type Zipper_List a = ([a],[a]) go_Forward :: Zipper_List a -> Zipper_List a go_Forward (x:xs, bs) = (xs, x:bs) go_Back :: Zipper_List a -> Zipper_List a go_Back (xs, b:bs) = (b:xs, bs) main = do let list_Ex = [1,2,3,4] print(go_Forward (list_Ex,[])) print(go_Back([4],[3,2,1])) When you compile and execute the above program, it will produce the following output − ([2,3,4],[1]) ([3,4],[2,1]) Here we are focusing on an element of the entire string while going forward or while coming backward. Print Page Previous Next Advertisements ”;

Haskell – Useful Resources

Haskell – Useful Resources ”; Previous Next The following resources contain additional information on Haskell. Please use them to get more in-depth knowledge on this. Useful Links on Haskell Haskell − Official Homepage of Haskell Haskell Wiki − Wikipedia Reference for Haskell Useful Books on Haskell To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;

Haskell – Input & Output

Haskell – Input & Output ”; Previous Next All the examples that we have discussed so far are static in nature. In this chapter, we will learn to communicate dynamically with the users. We will learn different input and output techniques used in Haskell. Files and Streams We have so far hard-coded all the inputs in the program itself. We have been taking inputs from static variables. Now, let us learn how to read and write from an external file. Let us create a file and name it “abc.txt”. Next, enter the following lines in this text file: “Welcome to Tutorialspoint. Here, you will get the best resource to learn Haskell.” Next, we will write the following code which will display the contents of this file on the console. Here, we are using the function readFile() which reads a file until it finds an EOF character. main = do let file = “abc.txt” contents <- readFile file putStrLn contents The above piece of code will read the file “abc.txt” as a String until it encounters any End of File character. This piece of code will generate the following output. Welcome to Tutorialspoint Here, you will get the best resource to learn Haskell. Observe that whatever it is printing on the terminal is written in that file. Command Line Argument Haskell also provides the facility to operate a file through the command prompt. Let us get back to our terminal and type “ghci”. Then, type the following set of commands − let file = “abc.txt” writeFile file “I am just experimenting here.” readFile file Here, we have created a text file called “abc.txt”. Next, we have inserted a statement in the file using the command writeFile. Finally, we have used the command readFile to print the contents of the file on the console. Our code will produce the following output − I am just experimenting here. Exceptions An exception can be considered as a bug in the code. It is a situation where the compiler does not get the expected output at runtime. Like any other good programming language, Haskell provides a way to implement exception handling. If you are familiar with Java, then you might know the Try-Catch block where we usually throw an error and catch the same in the catch block. In Haskell, we also have the same function to catch runtime errors. The function definition of try looks like “try :: Exception e => IO a -> IO (Either e a)”. Take a look at the following example code. It shows how you can catch the “Divide by Zero” exception. Live Demo import Control.Exception main = do result <- try (evaluate (5 `div` 0)) :: IO (Either SomeException Int) case result of Left ex -> putStrLn $ “Caught exception: ” ++ show ex Right val -> putStrLn $ “The answer was: ” ++ show val In the above example, we have used the inbuilt try function of the Control.Exception module, hence we are catching the exception beforehand. Above piece of code will yield below output in the screen. Caught exception: divide by zero Print Page Previous Next Advertisements ”;

Haskell – Modules

Haskell – Modules ”; Previous Next If you have worked on Java, then you would know how all the classes are bound into a folder called package. Similarly, Haskell can be considered as a collection of modules. Haskell is a functional language and everything is denoted as an expression, hence a Module can be called as a collection of similar or related types of functions. You can import a function from one module into another module. All the “import” statements should come first before you start defining other functions. In this chapter, we will learn the different features of Haskell modules. List Module List provides some wonderful functions to work with list type data. Once you import the List module, you have a wide range of functions at your disposal. In the following example, we have used some important functions available under the List module. Live Demo import Data.List main = do putStrLn(“Different methods of List Module”) print(intersperse ”.” “Tutorialspoint.com”) print(intercalate ” ” [“Lets”,”Start”,”with”,”Haskell”]) print(splitAt 7 “HaskellTutorial”) print (sort [8,5,3,2,1,6,4,2]) Here, we have many functions without even defining them. That is because these functions are available in the List module. After importing the List module, the Haskell compiler made all these functions available in the global namespace. Hence, we could use these functions. Our code will yield the following output − Different methods of List Module “T.u.t.o.r.i.a.l.s.p.o.i.n.t…c.o.m” “Lets Start with Haskell” (“Haskell”,”Tutorial”) [1,2,2,3,4,5,6,8] Char Module The Char module has plenty of predefined functions to work with the Character type. Take a look at the following code block − Live Demo import Data.Char main = do putStrLn(“Different methods of Char Module”) print(toUpper ”a”) print(words “Let us study tonight”) print(toLower ”A”) Here, the functions toUpper and toLower are already defined inside the Char module. It will produce the following output − Different methods of Char Module ”A” [“Let”,”us”,”study”,”tonight”] ”a” Map Module Map is an unsorted value-added pair type data type. It is a widely used module with many useful functions. The following example shows how you can use a predefined function available in the Map module. Live Demo import Data.Map (Map) import qualified Data.Map as Map –required for GHCI myMap :: Integer -> Map Integer [Integer] myMap n = Map.fromList (map makePair [1..n]) where makePair x = (x, [x]) main = print(myMap 3) It will produce the following output − fromList [(1,[1]),(2,[2]),(3,[3])] Set Module The Set module has some very useful predefined functions to manipulate mathematical data. A set is implemented as a binary tree, so all the elements in a set must be unique. Take a look at the following example code Live Demo import qualified Data.Set as Set text1 = “Hey buddy” text2 = “This tutorial is for Haskell” main = do let set1 = Set.fromList text1 set2 = Set.fromList text2 print(set1) print(set2) Here, we are modifying a String into a Set. It will produce the following output. Observe that the output set has no repetition of characters. fromList ” Hbdeuy” fromList ” HTaefhiklorstu” Custom Module Let’s see how we can create a custom module that can be called at other programs. To implement this custom module, we will create a separate file called “custom.hs” along with our “main.hs”. Let us create the custom module and define a few functions in it. custom.hs module Custom ( showEven, showBoolean ) where showEven:: Int-> Bool showEven x = do if x ”rem” 2 == 0 then True else False showBoolean :: Bool->Int showBoolean c = do if c == True then 1 else 0 Our Custom module is ready. Now, let us import it into a program. main.hs import Custom main = do print(showEven 4) print(showBoolean True) Our code will generate the following output − True 1 The showEven function returns True, as “4” is an even number. The showBoolean function returns “1” as the Boolean function that we passed into the function is “True”. Print Page Previous Next Advertisements ”;

Haskell – Quick Guide

Haskell – Quick Guide ”; Previous Next Haskell – Overview Haskell is a Functional Programming Language that has been specially designed to handle symbolic computation and list processing applications. Functional programming is based on mathematical functions. Besides Haskell, some of the other popular languages that follow Functional Programming paradigm include: Lisp, Python, Erlang, Racket, F#, Clojure, etc. In conventional programing, instructions are taken as a set of declarations in a specific syntax or format, but in the case of functional programing, all the computation is considered as a combination of separate mathematical functions. Going Functional with Haskell Haskell is a widely used purely functional language. Here, we have listed down a few points that make this language so special over other conventional programing languages such as Java, C, C++, PHP, etc. Functional Language − In conventional programing language, we instruct the compiler a series of tasks which is nothing but telling your computer “what to do” and “how to do?” But in Haskell we will tell our computer “what it is?” Laziness − Haskell is a lazy language. By lazy, we mean that Haskell won”t evaluate any expression without any reason. When the evaluation engine finds that an expression needs to be evaluated, then it creates a thunk data structure to collect all the required information for that specific evaluation and a pointer to that thunk data structure. The evaluation engine will start working only when it is required to evaluate that specific expression. Modularity − A Haskell application is nothing but a series of functions. We can say that a Haskell application is a collection of numerous small Haskell applications. Statically Typed − In conventional programing language, we need to define a series of variables along with their type. In contrast, Haskell is a type interference language. By the term, type interference language, we mean the Haskell compiler is intelligent enough to figure out the type of the variable declared, hence we need not explicitly mention the type of the variable used. Maintainability − Haskell applications are modular and hence, it is very easy and cost-effective to maintain them. Functional programs are more concurrent and they follow parallelism in execution to provide more accurate and better performance. Haskell is no exception; it has been developed in a way to handle multithreading effectively. Hello World It is a simple example to demonstrate the dynamism of Haskell. Take a look at the following code. All that we need is just one line to print “Hello Word” on the console. Live Demo main = putStrLn “Hello World” Once the Haskell compiler encounters the above piece of code, it promptly yields the following output − Hello World We will provide plenty of examples throughout this tutorial to showcase the power and simplicity of Haskell. Haskell – Environment Set Up We have set up the Haskell programing environment online at − https://www.tutorialspoint.com/compile_haskell_online.php This online editor has plenty of options to practice Haskell programing examples. Go to the terminal section of the page and type “ghci”. This command automatically loads Haskell compiler and starts Haskell online. You will receive the following output after using the ghci command. sh-4.3$ ghci GHCi,version7.8.4:http://www.haskell.org/ghc/:?forhelp Loading package ghc-prim…linking…done. Loading packageinteger gmp…linking… done. Loading package base…linking…done. Prelude> If you still want to use Haskell offline in your local system, then you need to download the available Haskell setup from its official webpage − https://www.haskell.org/downloads There are three different types of installers available in the market − Minimal Installer − It provides GHC (The Glasgow Haskell Compiler), CABAL (Common Architecture for Building Applications and Libraries), and Stack tools. Stack Installer − In this installer, the GHC can be downloaded in a cross-platform of managed toll chain. It will install your application globally such that it can update its API tools whenever required. It automatically resolves all the Haskell-oriented dependencies. Haskell Platform − This is the best way to install Haskell because it will install the entire platform in your machine and that to from one specific location. This installer is not distributive like the above two installers. We have seen different types of installer available in market now let us see how to use those installers in our machine. In this tutorial we are going to use Haskell platform installer to install Haskell compiler in our system. Environment Set Up in Windows To set up Haskell environment on your Windows computer, go to their official website https://www.haskell.org/platform/windows.html and download the Installer according to your customizable architecture. Check out your system’s architecture and download the corresponding setup file and run it. It will install like any other Windows application. You may need to update the CABAL configuration of your system. Environment Set Up in MAC To set up Haskell environment on your MAC system, go to their official website https://www.haskell.org/platform/mac.html and download the Mac installer. Environment Set Up in Linux Installing Haskell on a Linux-based system requires to run some command which is not that much easy like MAC and Windows. Yes, it is tiresome but it is reliable. You can follow the steps given below to install Haskell on your Linux system − Step 1 − To set up Haskell environment on your Linux system, go to the official website https://www.haskell.org/platform/linux.html and choose your distribution. You will find the following screen on your browser. Step 2 − Select your Distribution. In our case, we are using Ubuntu. After selecting this option, you will get the following page on your screen with the command to install the Haskell in our local system. Step 3 − Open a terminal by pressing Ctrl + Alt + T. Run the command “$ sudo apt-get install haskell-platform” and press Enter. It will automatically start downloading Haskell on your system after authenticating you with the root password. After installing, you will receive a confirmation message. Step 4 − Go to your terminal again and run the GHCI command. Once you get the Prelude prompt, you are ready to use Haskell on your local system.