strangerRidingCaml

16. Functional Programming Languages and Type Systems: Haskell, OCaml 본문

Type theory

16. Functional Programming Languages and Type Systems: Haskell, OCaml

woddlwoddl 2024. 5. 11. 02:42
728x90
Functional Programming Languages and Type Systems: Haskell, OCaml

Functional Programming Languages and Type Systems: Haskell, OCaml

Haskell and OCaml are both functional programming languages known for their strong static type systems and expressive features.

Haskell:

  • Haskell is a purely functional programming language with lazy evaluation.
  • It has a strong, static type system with type inference, which allows types to be inferred automatically.
  • Functions are first-class citizens in Haskell, meaning they can be passed as arguments, returned from other functions, and stored in data structures.
  • Haskell supports higher-order functions, pattern matching, and algebraic data types, making it well-suited for both mathematical and practical programming tasks.

OCaml:

  • OCaml is a multi-paradigm programming language with support for functional, imperative, and object-oriented programming styles.
  • It has a strong, static type system with type inference, similar to Haskell.
  • OCaml provides powerful pattern matching capabilities and supports algebraic data types and polymorphic variants.
  • It is often used for systems programming, compiler development, and scripting tasks.

Lab Activity: Functional Programming Concepts in Haskell

Let's implement a simple factorial function in Haskell to demonstrate functional programming concepts.


factorial :: Integer -> Integer
factorial 0 = 1
factorial n = n * factorial (n - 1)

main :: IO ()
main = do
  putStrLn "Factorial of 5:"
  print (factorial 5)
  

In the lab activity, we define a factorial function using pattern matching.

We then demonstrate the implementation by calculating the factorial of 5 and printing the result.

Lab Activity: Functional Programming Concepts in OCaml

Let's implement a simple factorial function in OCaml to demonstrate functional programming concepts.


let rec factorial n =
  match n with
  | 0 -> 1
  | _ -> n * factorial (n - 1)

let () =
  print_endline "Factorial of 5:";
  print_int (factorial 5);
  print_newline ()
  

In the lab activity, we define a factorial function using pattern matching.

We then demonstrate the implementation by calculating the factorial of 5 and printing the result.