package reparse-lwt

  1. Overview
  2. Docs
Reparse Lwt_stream.t input support

Install

Dune Dependency

Authors

Maintainers

Sources

reparse-v3.0.1.tbz
sha256=3c4a2bfdeca54627f2460b122e5359ec11338b7752271f4f1869826730559ba5
sha512=b26d33f112d0177e8b0cf7ace59a7b67b7fc22c146e6a57492875e4d4cca1a12da7cbdc181b76fc9be29c96267773a2c0445034b374633ba7bfef01b91c0b256

Description

char Lwt_stream.t parsing support for 'reparse'

Published: 30 Jun 2021

README

Reparse

Reparse is a monadic, recursive descent based, comprehensive parser construction library for ocaml.

Reparse Documentation

Getting Started

$ opam install reparse

Add reparse to dune,

(executable # or library
  (name hello_world)
  (public_name hello_world)
  (libraries reparse))

Example - Calculator

A calculator is the hello world of parsers. Here is an implementation in Reparse which supports +,-,* and / operations.

# #require "reparse";;
open Reparse.String

type expr =
  | Int of int
  | Add of expr * expr
  | Sub of expr * expr
  | Mult of expr * expr
  | Div of expr * expr

let skip_spaces = skip space

let binop : 'a t -> char -> 'b t -> ('a -> 'b -> 'c) -> 'c t =
 fun exp1 op exp2 f ->
  (exp1, skip_spaces *> char op <* skip_spaces, exp2)
  <$$$> fun e1 _ e2 -> f e1 e2

let integer : expr t =
  let+ d = skip_spaces *> digits <* skip_spaces in
  Int (int_of_string d)

let factor : expr t -> expr t =
 fun expr ->
  any [ char '(' *> skip_spaces *> expr <* skip_spaces <* char ')'; integer ]

let term : expr t -> expr t =
 fun factor ->
  recur (fun term ->
      let mult = binop factor '*' term (fun e1 e2 -> Mult (e1, e2)) in
      let div = binop factor '/' term (fun e1 e2 -> Div (e1, e2)) in
      mult <|> div <|> factor)

let expr : expr t =
  recur (fun expr ->
      let factor = factor expr in
      let term = term factor in
      let add = binop term '+' expr (fun e1 e2 -> Add (e1, e2)) in
      let sub = binop term '-' expr (fun e1 e2 -> Sub (e1, e2)) in
      any [ add; sub; term ] <?> "expr")

let rec eval : expr -> int = function
  | Int i -> i
  | Add (e1, e2) -> eval e1 + eval e2
  | Sub (e1, e2) -> eval e1 - eval e2
  | Mult (e1, e2) -> eval e1 * eval e2
  | Div (e1, e2) -> eval e1 / eval e2
# let ast = parse (create_input_from_string "1*2-4+3") expr ;;
val ast : (expr, string) result =
  Ok (Sub (Mult (Int 1, Int 2), Add (Int 4, Int 3)))

# eval @@ Result.get_ok (parse (create_input_from_string "12+1*10") expr);;
- : int = 22

More Examples

Dependencies (5)

  1. reparse = version
  2. cstruct >= "6.0.0"
  3. lwt >= "5.4.1"
  4. ocaml >= "4.10.0"
  5. dune >= "2.8"

Dev Dependencies (1)

  1. odoc with-doc

Used by (1)

  1. http-multipart-formdata >= "2.0.0" & < "3.0.0"

Conflicts

None

OCaml

Innovation. Community. Security.