1. Home
  2. /
  3. Haskell
  4. /
  5. Pure Functions

Pure Functions - Haskell Typing CST Test

Loading…

Pure Functions — Haskell Code

Demonstrates Haskell's pure functions, pattern matching, and list operations.

-- Define a custom data type
data Shape = Circle Float | Rectangle Float Float

-- Calculate area using pattern matching
area :: Shape -> Float
area (Circle r) = pi * r * r
area (Rectangle w h) = w * h

-- Higher-order functions
quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) = 
	let smaller = quicksort [a | a <- xs, a <= x]
		bigger = quicksort [a | a <- xs, a > x]
	in smaller ++ [x] ++ bigger

-- List operations
fibonacci :: [Integer]
fibonacci = 0 : 1 : zipWith (+) fibonacci (tail fibonacci)

-- Main function
main :: IO ()
main = do
	let shapes = [Circle 5.0, Rectangle 3.0 4.0, Circle 2.5]
	let areas = map area shapes

	putStrLn $ "Areas: " ++ show areas
	putStrLn $ "First 10 fibonacci: " ++ show (take 10 fibonacci)
	putStrLn $ "Sorted [3,1,4,1,5,9]: " ++ show (quicksort [3,1,4,1,5,9])

Haskell Language Guide

Haskell is a purely functional, statically typed programming language known for immutability, strong type inference, mathematical precision, and high reliability. It is widely used in finance, compilers, research, distributed systems, and correctness-critical software.

Primary Use Cases

  • ▸Pure functional application development
  • ▸Distributed systems
  • ▸Financial trading engines
  • ▸Compilers & language tooling
  • ▸Formal verification
  • ▸Research & algorithm modeling
  • ▸Simulation & high-assurance software

Notable Features

  • ▸Purely functional programming
  • ▸Lazy evaluation model
  • ▸Advanced type system (typeclasses, GADTs, HKTs)
  • ▸Strong type inference
  • ▸Immutability-first design
  • ▸Concise mathematical syntax

Origin & Creator

Developed by a committee of academics in 1990 led by Simon Peyton Jones, Paul Hudak, and Philip Wadler to create a standard pure functional language.

Industrial Note

Haskell excels in domains needing mathematical correctness, high-assurance code, compiler/tooling development, fintech trading systems, distributed ledgers, blockchain research, and formally verifiable system design.

More Haskell Typing Exercises

Haskell Factorial and RecursionHaskell Map and FilterHaskell Maybe TypeHaskell Zip and List ComprehensionHaskell Higher-Order FunctionsHaskell Pattern Matching on TuplesHaskell Recursion with GuardsHaskell Infinite ListsHaskell Function Composition

Practice Other Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypher