0% found this document useful (0 votes)
7 views

Haskell Programming

Haskell is a purely functional programming language that emphasizes immutability, lazy evaluation, and strong static typing with type inference. It supports higher-order functions, pattern matching, and monads for handling side effects, making it suitable for concurrent and parallel programming. The language has a rich ecosystem and community, providing various libraries and tools for developers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Haskell Programming

Haskell is a purely functional programming language that emphasizes immutability, lazy evaluation, and strong static typing with type inference. It supports higher-order functions, pattern matching, and monads for handling side effects, making it suitable for concurrent and parallel programming. The language has a rich ecosystem and community, providing various libraries and tools for developers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

l Haskell Programming Features

Functional Programming Paradigm: Haskell is a purely functional programming language


which means it treats computation as the evaluation of mathematical functions and avoids
changing state and mutable data. Functions in Haskell are first-class citizens; they can be
passed as arguments to other functions and returned as values from functions

Lazy Evaluation: Haskell uses lazy evaluation, also known as call-by-need evaluation. This
means that expressions are not evaluated until their results are actually needed. Lazy
evaluation can lead to more efficient programs, especially when dealing with infinite data
structures.

-* Static Typing and Type Inference: Haskell has a strong, static type system. However,
Haskell's type inference allows most types to be inferred by the compiler, reducing the need
for explicit type declarations. This helps catch type-related errors at compile-time, making
programs more robust.

Immutable Data: Data in Haskell is immutable, meaning once a data structure is created, it
cannot be changed. Any operation that appears to modify a data structure actually creates a
new copy with the desired changes. Immutability simplifies reasoning about the behavior of
This means that expressions are not evaluated until their results are actually needed. Lazy
evaluation can lead to more efficient programs, especially when dealing with infinite data
structures.This means that expressions are not evaluated until their results are actually
needed. Lazy evaluation can lead to more efficient programs, especially when dealing with
infinite data structures.

Higher-Order Functions: Haskell supports higher-order functions, allowing furograms and


enables safer concurrent programming.

functions to take other functions as arguments or return them as results. This feature enables
powerful abstractions and expressive code, facilitating the use of functions as building blocks
for complex behaviors.

Type Classes and Polymorphism: Haskell's type classes allow for ad-hoc polymorphism.
Type classes define a set of functions that can work on any type that is an instance of that
class. That enables code reuse and generic programming while ensuring type safety.

Pattern Matching: Pattern matching is a fundamental feature in Haskell. It allows the


programmer to destructure data and match it against specific patterns, making it easier to
work with complex data structures and improve code readability.
Monads and I/O Handling: Haskell uses monads to handle side effects in a pure functional
way. Monads provide a structured approach to I/O operations, allowing impure actions to be
encapsulated within the functional paradigm, maintaining referential transparency.

Concurrency and Parallelism: Haskell provides robust support for concurrent and parallel
programming. Haskell's pure functional nature makes it well-suited for concurrent
programming, and its runtime system supports lightweight threads and multicore parallelism.
Strong Community and Package Ecosystem: Haskell has a vibrant and active community
that contributes to libraries and tools, creating a rich ecosystem. The Haskell Platform
provides a comprehensive collection of libraries for various purposes, enabling developers to
leverage existing solutions for their projects.

Numbers: Integers and Floating-Point Numbers:

-- Integer (whole numbers) type -- Addition


x :: Int sumResult :: Int
x=5 sumResult = 5 + 3 -- results in 8

-- Subtraction
-- Floating-point number type difference :: Int
y :: Float difference = 10 - 4 -- results in 6
y = 3.14
-- Multiplication
-- Double-precision floating-point productResult :: Int
z :: Double productResult = 3 * 7 -- results in 21
z = 3.141592653589793
-- Division
quotient :: Float
quotient = 10 / 3 -- results in 3.3333...

Lists: Creating Lists:

-- List of Integers

numbers :: [Int]
numbers = [1, 2, 3, 4, 5]

-- List of Mixed Types

mixedList :: [Either Int String]


mixedList = [Left 1, Right "hello", Left 2, Right "world"]
—---------------------------------------------------------------------
-- Concatenation

combinedList :: [Int]
combinedList = [1, 2, 3] ++ [4, 5, 6] -- results in [1, 2, 3, 4, 5, 6]
-- Accessing Elements by Index (0-based)

elementAtIndex :: Int
elementAtIndex = numbers !! 2 -- gets the third element (index 2), which is 3

-- Head and Tail (First Element and Rest of the List)

firstElement :: Int
firstElement = head numbers -- gets the first element, which is 1

restOfList :: [Int]
restOfList = tail numbers -- gets the list without the first element, [2, 3, 4, 5]

-- List Comprehension

evenNumbers :: [Int]
evenNumbers = [x | x <- numbers, x `mod` 2 == 0] -- results in [2, 4]

Tuples: Creating Tuples:

-- Pair of Integers
pair :: (Int, Int)
pair = (1, 2)

-- Triple with Mixed Types


person :: (String, Int, Bool)
person = ("Alice", 30, True)

-- Accessing Elements
name :: String
name = fst person -- gets the first element of the tuple, "Alice"

age :: Int
age = snd person -- gets the second element of the tuple, 30
Inbuilt Data Types

-- Integers and Floating-Point Numbers -- Lists


age :: Int numbers :: [Int]
age = 25 //int age=25 numbers = [1, 2, 3, 4, 5]

height :: Float -- Tuples


height = 5.9 person :: (String, Int, Bool)
person = ("Alice", 30, True)
-- Booleans
isAdult :: Bool -- Maybe Type (for handling optional values)
isAdult = age >= 18 maybeName :: Maybe String
maybeName = Just "Bob"
-- Characters
firstInitial :: Char -- Either Type (for handling results with
firstInitial = 'J' possibility of errors)
result :: Either String Int
-- Strings result = Right 42
fullName :: String
fullName = "John Doe"

-- Custom Data Type (Enum)


data Day = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday
deriving (Show)

-- Pattern Matching with Custom Data Type -- Example Usage


isWeekend :: Day -> Bool main :: IO ()
isWeekend Saturday = True main = do
isWeekend Sunday = True putStrLn (greet fullName)
isWeekend _ = False print ("Is Adult? " ++ show isAdult)
print ("Is Saturday a weekend day? " ++
-- Example Function show (isWeekend Saturday))
greet :: String -> String
greet name = "Hello, " ++ name ++ "!"

In Haskell, Maybe is a data type used to represent optional values. It is a way to


handle computations that might fail. The Maybe type can have one of two values:
Just a: Represents a value of type a (where a can be any data type), indicating that a
valid result is present.

Nothing: Represents the absence of a value, indicating that the computation has
failed or that no valid result is available.

Just 42 means that the result of a computation is the integer 42.

Example for Show function:

-- Using show to convert an integer to a string


number :: Int
number = 42

-- Using show to convert a boolean to a string


isTrue :: Bool
isTrue = True

-- Converting values to strings and concatenating them


output :: String
output = "The number is " ++ show number ++ " and isTrue is " ++ show isTrue

-- Output:
-- "The number is 42 and isTrue is True"

Functional composition in haskell

● It is a technique where you combine two or more functions to create a new


function.
● It allows you to create complex functions by composing simpler ones together.
● The composition operator in Haskell is denoted by . (a period).
doubleThenIncrement is a composition of the double and increment functions.
When you call doubleThenIncrement 3, it first doubles the input (resulting in 6) and
then increments the result by 1, giving you the final result of 7.

Example 2:

square :: Int -> Int


square x = x * x

addTen :: Int -> Int


addTen x = x + 10

toString :: Int -> String


toString x = show x

funcomp:: Int -> String


funcomp= toString . addTen . square

result :: String
result = funcomp 5
-- The result will be "35" because (5^2) + 10 = 35, and then it's converted to a string
Functions

Guards is a concept that is very similar to pattern matching.

In pattern matching, we usually match one or more expressions, but we


use guards to test some property of an expression.

For first-time users, guards can look very similar to If-Else statements,
but they are functionally different.

Where Clause : Where is a keyword or inbuilt function that can be


used at runtime to generate a desired output. It can be very helpful when
function calculation becomes complex.

Recursion:
Higher Order Function
Till now, what we have seen is that Haskell functions take one type as
input and produce another type as output.

Higher Order Functions are a unique feature of Haskell where you can use
a function as an input or output argument.

applyTwice :: (a -> a) -> a -> a -- Usage


applyTwice f x = f (f x)

-- Example functions to demonstrate result1 :: Int


usage result1 = doubleTwice 5
double :: Int -> Int -- Result: 20 (double(double(5)) =20)
double x = x * 2
result2 :: Int
square :: Int -> Int result2 = squareTwice 3
square x = x * x -- Result: 81 (square(square(3)) = 81)

-- Usage examples
doubleTwice :: Int -> Int
doubleTwice = applyTwice double

squareTwice :: Int -> Int


squareTwice = applyTwice square
lambda expressions are anonymous functions, allowing you to create functions
without explicitly naming them. Lambda expressions are useful when you need a
simple function for a short period and don't want to formally define it using the name
= ... syntax.

-- Lambda expression that squares a number


square :: Int -> Int
square = \x -> x * x

-- Usage
result :: Int
result = square 5
-- Result: 25 (5 * 5 = 25)

Haskell Inbuilt Functions


—---------------------------------------------------------------------------------------

let x = [1..10]
print (x)
print (head x)
print (tail x)
print (last x)
print (init x)
print (null x)
print (reverse x)
print (length x)
main = print(take 5 ([1 .. 10]))
main = print(drop 5 ([1 .. 10]))
print (maximum x)
print (minimum x)
print (sum x)
print (product x)

putStrLn "Does it contain 786?"


print (elem 786 (x))

You might also like