_id stringlengths 64 64 | repository stringlengths 6 84 | name stringlengths 4 110 | content stringlengths 0 248k | license null | download_url stringlengths 89 454 | language stringclasses 7
values | comments stringlengths 0 74.6k | code stringlengths 0 248k |
|---|---|---|---|---|---|---|---|---|
abfc76b99b86f5f3c6b168afca2f74ad086f30010cbed18c0f927f1387a2d653 | michaelklishin/neocons | batch.clj | Copyright ( c ) 2011 - 2015 , , and The ClojureWerkz
Team
;;
;; The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 ( -1.0.php )
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns clojurewerkz.neocons.rest.batch
"Batch operation execution"
(:require [clojurewerkz.neocons.rest :as rest]
[clojurewerkz.neocons.rest.records :as rec]
[cheshire.core :as json])
(:import clojurewerkz.neocons.rest.Connection))
;;
;; API
;;
(defn perform
"Submits a batch of operations for execution, returning a lazy sequence of results. Operations must include
two keys:
:method (\"POST\", \"GET\", etc)
:to (a path relative to the database root URI)
and may or may not include
:data (a map of what would be in the request body in cases non-batch API was used)
:id (request id that is used to refer to previously executed operations in the same batch)
If you need to insert a batch of nodes at once, consider using neocons.rest.nodes/create-batch.
See -api-batch-ops.html for more information."
[^Connection connection ops]
(let [{:keys [status headers body]} (rest/POST connection (get-in connection [:endpoint :batch-uri])
:body (json/encode ops))
payload (map :body (json/decode body true))]
(map rec/instantiate-record-from payload)))
| null | https://raw.githubusercontent.com/michaelklishin/neocons/30f30e95686a01f7a34082600bc1221877c2acbd/src/clojure/clojurewerkz/neocons/rest/batch.clj | clojure |
The use and distribution terms for this software are covered by the
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
API
| Copyright ( c ) 2011 - 2015 , , and The ClojureWerkz
Team
Eclipse Public License 1.0 ( -1.0.php )
(ns clojurewerkz.neocons.rest.batch
"Batch operation execution"
(:require [clojurewerkz.neocons.rest :as rest]
[clojurewerkz.neocons.rest.records :as rec]
[cheshire.core :as json])
(:import clojurewerkz.neocons.rest.Connection))
(defn perform
"Submits a batch of operations for execution, returning a lazy sequence of results. Operations must include
two keys:
:method (\"POST\", \"GET\", etc)
:to (a path relative to the database root URI)
and may or may not include
:data (a map of what would be in the request body in cases non-batch API was used)
:id (request id that is used to refer to previously executed operations in the same batch)
If you need to insert a batch of nodes at once, consider using neocons.rest.nodes/create-batch.
See -api-batch-ops.html for more information."
[^Connection connection ops]
(let [{:keys [status headers body]} (rest/POST connection (get-in connection [:endpoint :batch-uri])
:body (json/encode ops))
payload (map :body (json/decode body true))]
(map rec/instantiate-record-from payload)))
|
1e8b625f10a7217eecbd6b37300b9f2105afbf40a2e2bd8c766cc45c7c8d9abe | unclebob/AdventOfCode2020 | core_spec.clj | (ns day5.core-spec
(:require [speclj.core :refer :all]
[day5.core :refer :all]))
(describe "decode seat id"
(it "decodes"
(should= 127 (seat-id "BBBBBBB"))
(should= 81 (seat-id "BLBLFLR"))
(should= 357 (seat-id "FBFBBFFRLR"))))
(describe "solutions"
(it "solved#1"
(should= 922 (solve-1)))
(it "solved#2"
(should= 747 (solve-2))
)) | null | https://raw.githubusercontent.com/unclebob/AdventOfCode2020/fc4ba9ad042cbcc48dfa5947373ab46b750d89e5/day5/spec/day5/core_spec.clj | clojure | (ns day5.core-spec
(:require [speclj.core :refer :all]
[day5.core :refer :all]))
(describe "decode seat id"
(it "decodes"
(should= 127 (seat-id "BBBBBBB"))
(should= 81 (seat-id "BLBLFLR"))
(should= 357 (seat-id "FBFBBFFRLR"))))
(describe "solutions"
(it "solved#1"
(should= 922 (solve-1)))
(it "solved#2"
(should= 747 (solve-2))
)) | |
429e97b9da7c95184943da90a10f7a84243c25c415fea9ee4cb582f372190539 | abdulapopoola/SICPBook | Ex2.01.scm | #lang planet neil/sicp
(define (numer x) (car x))
(define (denom x) (cdr x))
XNOR is true when x and y have the same sign
(define (xnor x y)
(or (and x y)
(and (not x) (not y))))
(define (make-rat n d)
(let ((abs-n (abs n))
(abs-d (abs d)))
(if (xnor
(positive? n)
(positive? d))
(cons abs-n abs-d)
(cons (- abs-n) abs-d))))
(make-rat 2 3)
(make-rat 2 -3)
(make-rat -2 3)
(make-rat -2 -3)
| null | https://raw.githubusercontent.com/abdulapopoola/SICPBook/c8a0228ebf66d9c1ddc5ef1fcc1d05d8684f090a/Chapter%202/2.1/Ex2.01.scm | scheme | #lang planet neil/sicp
(define (numer x) (car x))
(define (denom x) (cdr x))
XNOR is true when x and y have the same sign
(define (xnor x y)
(or (and x y)
(and (not x) (not y))))
(define (make-rat n d)
(let ((abs-n (abs n))
(abs-d (abs d)))
(if (xnor
(positive? n)
(positive? d))
(cons abs-n abs-d)
(cons (- abs-n) abs-d))))
(make-rat 2 3)
(make-rat 2 -3)
(make-rat -2 3)
(make-rat -2 -3)
| |
3c5fe2f6fa62d1425b758b506b88ebbf987c3f5d0ebb7e3e2f036affa9dc5982 | Mishio595/disml | disml.ml | *
{ 2 Dis.ml - An OCaml library for interfacing with the Discord API }
{ 3 Example }
{ [
open Async
open Core
open Disml
open Models
( * Create a function to handle message_create .
{2 Dis.ml - An OCaml library for interfacing with the Discord API}
{3 Example}
{[
open Async
open Core
open Disml
open Models
(* Create a function to handle message_create. *)
let check_command (Event.MessageCreate.{message}) =
if String.is_prefix ~prefix:"!ping" message.content then
Message.reply message "Pong!" >>> ignore
let main () =
(* Register the event handler *)
Client.message_create := check_command;
(* Start the client. It's recommended to load the token from an env var or other config file. *)
Client.start "My token" >>> ignore
let _ =
Launch the Async scheduler . You must do this for anything to work .
Scheduler.go_main ~main ()
]}
*)
* The primary interface for connecting to Discord and handling gateway events .
module Client = Client
(** Caching module. {!Cache.cache} is an {{!Async.Mvar.Read_write.t}Mvar}, which is always filled, containing an immutable cache record to allow for safe, concurrent access. *)
module Cache = Cache
* Raw HTTP abstractions for Discord 's REST API .
module Http = struct
include Http
(** Internal module for resolving endpoints *)
module Endpoints = Endpoints
(** Internal module for handling rate limiting *)
module Ratelimits = Rl
end
(** Gateway connection super module. *)
module Gateway = struct
(** Internal module used for dispatching events. *)
module Dispatch = Dispatch
(** Internal module for representing events. *)
module Event = Event
* Internal module for representing Discord 's opcodes .
module Opcode = Opcode
* manager
module Sharder = Sharder
end
* Super module for all Discord object types .
module Models = struct
(** Represents a user's activity. *)
module Activity = Activity
(** Represents a message attachment. *)
module Attachment = Attachment
(** Represents a ban object. *)
module Ban = Ban
(** Represents a full channel object. *)
module Channel = Channel
(** Represents solely a channel ID. REST operations can be performed without the full object overhead using this. *)
module Channel_id = Channel_id
(** Represents an embed object. *)
module Embed = Embed
(** Represents an emoji, both custom and unicode. *)
module Emoji = Emoji
(** Represents a guild object, also called a server. *)
module Guild = Guild
(** Represents solely a guild ID. REST operations can be performed without the full object overhead using this. *)
module Guild_id = Guild_id
(** Represents a user in the context of a guild. *)
module Member = Member
(** Represents a message object in any channel. *)
module Message = Message
(** Represents solely a message ID. REST operations can be performed without the full object overhead using this. *)
module Message_id = Message_id
* Represents a permission integer as bitmask , allowing for constant set representation .
module Permissions = struct
include Permissions
module Overwrite = Overwrites
end
(** Represents a user presence. See {!Models.Event.PresenceUpdate}. *)
module Presence = Presence
(** Represents an emoji used to react to a message. *)
module Reaction = Reaction
(** Represents a role object. *)
module Role = Role
(** Represents solely a role ID. REST operations can be performed without the full object overhead using this. *)
module Role_id = Role_id
(** Represents a Discord ID. *)
module Snowflake = Snowflake
(** Represents a user object. *)
module User = User
(** Represents solely a user ID. REST operations can be performed without the full object overhead using this. *)
module User_id = User_id
(** Represents the structures received over the gateway. *)
module Event = Event_models
end
| null | https://raw.githubusercontent.com/Mishio595/disml/cbb1e47a6d358eace03790c07a1b85641f4ca366/lib/disml.ml | ocaml | Create a function to handle message_create.
Register the event handler
Start the client. It's recommended to load the token from an env var or other config file.
* Caching module. {!Cache.cache} is an {{!Async.Mvar.Read_write.t}Mvar}, which is always filled, containing an immutable cache record to allow for safe, concurrent access.
* Internal module for resolving endpoints
* Internal module for handling rate limiting
* Gateway connection super module.
* Internal module used for dispatching events.
* Internal module for representing events.
* Represents a user's activity.
* Represents a message attachment.
* Represents a ban object.
* Represents a full channel object.
* Represents solely a channel ID. REST operations can be performed without the full object overhead using this.
* Represents an embed object.
* Represents an emoji, both custom and unicode.
* Represents a guild object, also called a server.
* Represents solely a guild ID. REST operations can be performed without the full object overhead using this.
* Represents a user in the context of a guild.
* Represents a message object in any channel.
* Represents solely a message ID. REST operations can be performed without the full object overhead using this.
* Represents a user presence. See {!Models.Event.PresenceUpdate}.
* Represents an emoji used to react to a message.
* Represents a role object.
* Represents solely a role ID. REST operations can be performed without the full object overhead using this.
* Represents a Discord ID.
* Represents a user object.
* Represents solely a user ID. REST operations can be performed without the full object overhead using this.
* Represents the structures received over the gateway. | *
{ 2 Dis.ml - An OCaml library for interfacing with the Discord API }
{ 3 Example }
{ [
open Async
open Core
open Disml
open Models
( * Create a function to handle message_create .
{2 Dis.ml - An OCaml library for interfacing with the Discord API}
{3 Example}
{[
open Async
open Core
open Disml
open Models
let check_command (Event.MessageCreate.{message}) =
if String.is_prefix ~prefix:"!ping" message.content then
Message.reply message "Pong!" >>> ignore
let main () =
Client.message_create := check_command;
Client.start "My token" >>> ignore
let _ =
Launch the Async scheduler . You must do this for anything to work .
Scheduler.go_main ~main ()
]}
*)
* The primary interface for connecting to Discord and handling gateway events .
module Client = Client
module Cache = Cache
* Raw HTTP abstractions for Discord 's REST API .
module Http = struct
include Http
module Endpoints = Endpoints
module Ratelimits = Rl
end
module Gateway = struct
module Dispatch = Dispatch
module Event = Event
* Internal module for representing Discord 's opcodes .
module Opcode = Opcode
* manager
module Sharder = Sharder
end
* Super module for all Discord object types .
module Models = struct
module Activity = Activity
module Attachment = Attachment
module Ban = Ban
module Channel = Channel
module Channel_id = Channel_id
module Embed = Embed
module Emoji = Emoji
module Guild = Guild
module Guild_id = Guild_id
module Member = Member
module Message = Message
module Message_id = Message_id
* Represents a permission integer as bitmask , allowing for constant set representation .
module Permissions = struct
include Permissions
module Overwrite = Overwrites
end
module Presence = Presence
module Reaction = Reaction
module Role = Role
module Role_id = Role_id
module Snowflake = Snowflake
module User = User
module User_id = User_id
module Event = Event_models
end
|
f295a0fb5b5a6e457666922d324181208c8dbd4aa0f078dd5a073dcd52a1b7bc | brevis-us/brevis | cone.clj | (ns us.brevis.shape.cone
(:import [us.brevis BrShape])
(:require [brevis-utils.parameters :as parameters])
(:use [us.brevis vector]
[us.brevis.shape.core]))
(defn create-cone
"Create a cone object."
([]
(create-cone 1 1))
([length base]
(let [result (BrShape/createCone length base (parameters/get-param :gui))]
result)))
| null | https://raw.githubusercontent.com/brevis-us/brevis/de51c173279e82cca6d5990010144167050358a3/src/main/clojure/us/brevis/shape/cone.clj | clojure | (ns us.brevis.shape.cone
(:import [us.brevis BrShape])
(:require [brevis-utils.parameters :as parameters])
(:use [us.brevis vector]
[us.brevis.shape.core]))
(defn create-cone
"Create a cone object."
([]
(create-cone 1 1))
([length base]
(let [result (BrShape/createCone length base (parameters/get-param :gui))]
result)))
| |
7d5078ac44ab41ccd96ad68e66d92690f18dcc9c927030668340c66e416247df | shenxs/about-scheme | transhcan.rkt | #lang racket
(call/cc (lambda (k) (* 5 4)))
(call/cc (lambda (k) (* 5 (k 4))))
;;a list of number --> a number
(define (prducrt ls)
(call/cc (lambda (break)
(let f ([ls ls])
(cond
[(empty? ls) 1]
[(= (first ls) 0) (break 0)]
[else (* (first ls) (f (rest ls)))])))))
(prducrt '(1 2 3 4 5 6 0 2434 45))
(let ([x (call/cc (lambda (k) k))])
(x (lambda (nothing)
(begin (displayln nothing)
"hi"))))
;;好像明白一点什么叫延续了
(define lwp-list '())
将一个任务加入list的结尾
(define (lwp thunk)
(set! lwp-list (append lwp-list (list thunk))))
;;从列表取出一个任务来执行
(define (start)
(let ([p (first lwp-list)])
(set! lwp-list (rest lwp-list))
(p)))
(define (pause)
(call/cc (lambda (k)
(lwp (lambda () (k #f)))
(start))))
(lwp (lambda ()
(let f ()
(pause)
(display "h")
(f))))
(lwp (lambda () (let f () (pause) (display "e") (f))))
(lwp (lambda () (let f () (pause) (display "y") (f))))
(lwp (lambda () (let f () (pause) (display "!") (f))))
(lwp (lambda () (let f () (pause) (newline) (f))))
;;(start)
((first)) (list (lambda () (let f () (pause) (display "f") (f) )))
| null | https://raw.githubusercontent.com/shenxs/about-scheme/d458776a62cb0bbcbfbb2a044ed18b849f26fd0f/TSPL/transhcan.rkt | racket | a list of number --> a number
好像明白一点什么叫延续了
从列表取出一个任务来执行
(start) | #lang racket
(call/cc (lambda (k) (* 5 4)))
(call/cc (lambda (k) (* 5 (k 4))))
(define (prducrt ls)
(call/cc (lambda (break)
(let f ([ls ls])
(cond
[(empty? ls) 1]
[(= (first ls) 0) (break 0)]
[else (* (first ls) (f (rest ls)))])))))
(prducrt '(1 2 3 4 5 6 0 2434 45))
(let ([x (call/cc (lambda (k) k))])
(x (lambda (nothing)
(begin (displayln nothing)
"hi"))))
(define lwp-list '())
将一个任务加入list的结尾
(define (lwp thunk)
(set! lwp-list (append lwp-list (list thunk))))
(define (start)
(let ([p (first lwp-list)])
(set! lwp-list (rest lwp-list))
(p)))
(define (pause)
(call/cc (lambda (k)
(lwp (lambda () (k #f)))
(start))))
(lwp (lambda ()
(let f ()
(pause)
(display "h")
(f))))
(lwp (lambda () (let f () (pause) (display "e") (f))))
(lwp (lambda () (let f () (pause) (display "y") (f))))
(lwp (lambda () (let f () (pause) (display "!") (f))))
(lwp (lambda () (let f () (pause) (newline) (f))))
((first)) (list (lambda () (let f () (pause) (display "f") (f) )))
|
0deb576ee2c94112982c4ea743b5fa7fa9f277092e0d9aab49011899e8529eac | autolwe/autolwe | ParserTools.ml | (* * Useful functions for parsers and error messages *)
open Abbrevs
(* Use this in your lexer *)
exception LexerError of string
exception ParserError
type parse_error =
{ pe_char_start : int
; pe_char_end : int
; pe_line_start : int
; pe_line_char_start : int
; pe_line_char_end : int
; pe_line : string
; pe_msg : string }
exception ParseError of parse_error
let charpos_to_linepos s cp =
let module E = struct exception Found of int * int * string end in
let lines = BatString.nsplit s ~by:"\n" in
let cur_line = ref 1 in
let cur_cp = ref cp in
try
List.iter
(fun ls ->
let len = String.length ls in
if !cur_cp < len then
raise (E.Found(!cur_line,!cur_cp,ls));
incr cur_line;
cur_cp := !cur_cp - len - 1
)
lines;
assert false
with
E.Found(l,cp,s) -> (l,cp,s)
let wrap_error f s =
let sbuf = Lexing.from_string s in
try
`ParseOk (f sbuf)
with
| LexerError msg ->
let start_pos = Lexing.lexeme_start sbuf in
let end_pos = Lexing.lexeme_start sbuf in
let len = end_pos - start_pos in
let (line_pos,lstart_pos,line) = charpos_to_linepos s start_pos in
`ParseError
{ pe_char_start = start_pos
; pe_char_end = end_pos
; pe_line_start = line_pos
; pe_line_char_start = lstart_pos
; pe_line_char_end = lstart_pos+len
; pe_line = line
; pe_msg = msg }
| ParserError ->
let start_pos = Lexing.lexeme_start sbuf in
let end_pos = Lexing.lexeme_start sbuf in
let len = end_pos - start_pos in
let (line_pos,lstart_pos,line) = charpos_to_linepos s start_pos in
`ParseError
{ pe_char_start = start_pos
; pe_char_end = end_pos
; pe_line_start = line_pos
; pe_line_char_start = lstart_pos
; pe_line_char_end = lstart_pos+len
; pe_line = line
; pe_msg = "parse error" }
| e ->
failwith
(F.sprintf "Unexpected error while lexing/parsing: %s,\n%s"
(Printexc.to_string e)
(Printexc.get_backtrace ()))
let error_string file pe =
(F.sprintf "%s:%i:%i %i:%i error: %s\n"
file
pe.pe_line_start pe.pe_line_char_start
pe.pe_line_start pe.pe_line_char_end
pe.pe_msg)
^(F.sprintf "%s\n" pe.pe_line)
^(F.sprintf "%s%s\n" (String.make pe.pe_line_char_start ' ') "^")
let wrap_error_exn f s =
match wrap_error f s with
| `ParseOk pres -> pres
| `ParseError(pinfo) ->
raise (ParseError(pinfo))
let parse ~parse file s =
begin match parse s with
| `ParseOk pres -> pres
| `ParseError(pinfo) ->
let s = error_string file pinfo in
failwith s
end
| null | https://raw.githubusercontent.com/autolwe/autolwe/3452c3dae06fc8e9815d94133fdeb8f3b8315f32/src/Util/ParserTools.ml | ocaml | * Useful functions for parsers and error messages
Use this in your lexer |
open Abbrevs
exception LexerError of string
exception ParserError
type parse_error =
{ pe_char_start : int
; pe_char_end : int
; pe_line_start : int
; pe_line_char_start : int
; pe_line_char_end : int
; pe_line : string
; pe_msg : string }
exception ParseError of parse_error
let charpos_to_linepos s cp =
let module E = struct exception Found of int * int * string end in
let lines = BatString.nsplit s ~by:"\n" in
let cur_line = ref 1 in
let cur_cp = ref cp in
try
List.iter
(fun ls ->
let len = String.length ls in
if !cur_cp < len then
raise (E.Found(!cur_line,!cur_cp,ls));
incr cur_line;
cur_cp := !cur_cp - len - 1
)
lines;
assert false
with
E.Found(l,cp,s) -> (l,cp,s)
let wrap_error f s =
let sbuf = Lexing.from_string s in
try
`ParseOk (f sbuf)
with
| LexerError msg ->
let start_pos = Lexing.lexeme_start sbuf in
let end_pos = Lexing.lexeme_start sbuf in
let len = end_pos - start_pos in
let (line_pos,lstart_pos,line) = charpos_to_linepos s start_pos in
`ParseError
{ pe_char_start = start_pos
; pe_char_end = end_pos
; pe_line_start = line_pos
; pe_line_char_start = lstart_pos
; pe_line_char_end = lstart_pos+len
; pe_line = line
; pe_msg = msg }
| ParserError ->
let start_pos = Lexing.lexeme_start sbuf in
let end_pos = Lexing.lexeme_start sbuf in
let len = end_pos - start_pos in
let (line_pos,lstart_pos,line) = charpos_to_linepos s start_pos in
`ParseError
{ pe_char_start = start_pos
; pe_char_end = end_pos
; pe_line_start = line_pos
; pe_line_char_start = lstart_pos
; pe_line_char_end = lstart_pos+len
; pe_line = line
; pe_msg = "parse error" }
| e ->
failwith
(F.sprintf "Unexpected error while lexing/parsing: %s,\n%s"
(Printexc.to_string e)
(Printexc.get_backtrace ()))
let error_string file pe =
(F.sprintf "%s:%i:%i %i:%i error: %s\n"
file
pe.pe_line_start pe.pe_line_char_start
pe.pe_line_start pe.pe_line_char_end
pe.pe_msg)
^(F.sprintf "%s\n" pe.pe_line)
^(F.sprintf "%s%s\n" (String.make pe.pe_line_char_start ' ') "^")
let wrap_error_exn f s =
match wrap_error f s with
| `ParseOk pres -> pres
| `ParseError(pinfo) ->
raise (ParseError(pinfo))
let parse ~parse file s =
begin match parse s with
| `ParseOk pres -> pres
| `ParseError(pinfo) ->
let s = error_string file pinfo in
failwith s
end
|
630b3efbdaf9b40d55128f5cdf62bb52861c0291ee18d56cb3fe3e25718e1cb4 | 1Jajen1/Brokkr | BlockState.hs | # LANGUAGE TemplateHaskell #
# LANGUAGE PatternSynonyms #
# LANGUAGE ViewPatterns #
# LANGUAGE AllowAmbiguousTypes #
# LANGUAGE DataKinds #
{-# LANGUAGE GADTs #-}
# OPTIONS_GHC -Wno - incomplete - patterns -Wno - missing - export - lists -Wno - unused - local - binds #
--{-# OPTIONS_GHC -ddump-simpl -dsuppress-all #-}
module Block.Internal.BlockState where
import Block.Internal.TH
import Data.Coerce
import GHC.TypeLits
newtype BlockState = BlockState Int
deriving newtype (Eq, Show) -- TODO Generate better show instance
-- Aux types TODO Autogen some of these. Especially the boolean equivalents
-- Or at least autogent the instances, that should not be hard!
class ToId a where
toId :: a -> Int
class FromId a where
fromId :: Int -> a
class Cardinality a where
cardinality :: Int
data Facing (up :: Bool) (down :: Bool) where
North :: Facing up down
East :: Facing up down
South :: Facing up down
West :: Facing up down
Up :: Facing 'True down
Down :: Facing up 'True
deriving stock instance Show (Facing 'True 'True )
deriving stock instance Show (Facing 'False 'False)
deriving stock instance Show (Facing 'False 'True )
deriving stock instance Show (Facing 'True 'False)
deriving stock instance Eq (Facing 'True 'True )
deriving stock instance Eq (Facing 'False 'False)
deriving stock instance Eq (Facing 'False 'True )
deriving stock instance Eq (Facing 'True 'False)
instance FromId (Facing 'False 'False) where
fromId 0 = North
fromId 1 = South
fromId 2 = West
fromId 3 = East
instance FromId (Facing 'True 'True) where
fromId 0 = North
fromId 1 = South
fromId 2 = West
fromId 3 = East
fromId 4 = Up
fromId 5 = Down
instance FromId (Facing 'False 'True) where
fromId 0 = Down
fromId 1 = North
fromId 2 = South
fromId 3 = West
fromId 4 = East
instance ToId (Facing 'False 'False) where
toId North = 0
toId East = 1
toId South = 2
toId West = 3
instance ToId (Facing 'True 'True) where
toId North = 0
toId East = 1
toId South = 2
toId West = 3
toId Up = 4
toId Down = 5
instance ToId (Facing 'False 'True) where
toId North = 1
toId East = 2
toId South = 3
toId West = 4
toId Down = 0
instance Cardinality (Facing 'False 'False) where
cardinality = 4
instance Cardinality (Facing 'True 'False) where
cardinality = 5
instance Cardinality (Facing 'False 'True) where
cardinality = 5
instance Cardinality (Facing 'True 'True) where
cardinality = 6
data Attached (up :: Bool) (down :: Bool) (side :: Facing up down) = Attached | NotAttached
instance FromId (Attached up down side) where
fromId 0 = Attached
fromId 1 = NotAttached
instance ToId (Attached up down side) where
toId Attached = 0
toId NotAttached = 1
instance Cardinality (Attached up down side) where
cardinality = 2
data WallAttached (side :: Facing 'False 'False) = Low | Tall | None
instance FromId (WallAttached side) where
fromId 0 = None
fromId 1 = Low
fromId 2 = Tall
instance ToId (WallAttached side) where
toId None = 0
toId Low = 1
toId Tall = 2
instance Cardinality (WallAttached s) where
cardinality = 3
data Waterlogged = Waterlogged | NotWaterlogged
instance FromId Waterlogged where
fromId 0 = Waterlogged
fromId 1 = NotWaterlogged
instance ToId Waterlogged where
toId Waterlogged = 0
toId NotWaterlogged = 1
instance Cardinality Waterlogged where
cardinality = 2
data Powered = Powered | NotPowered
instance FromId Powered where
fromId 0 = Powered
fromId 1 = NotPowered
instance ToId Powered where
toId Powered = 0
toId NotPowered = 1
instance Cardinality Powered where
cardinality = 2
data Face (bell :: Bool) where
OnFloor :: Face bell
OnWall :: Face 'False
OnCeiling :: Face bell
OnSingleWall :: Face 'True
OnDoubleWall :: Face 'True
instance FromId (Face 'False) where
fromId 0 = OnFloor
fromId 1 = OnWall
fromId 2 = OnCeiling
instance ToId (Face 'False) where
toId OnFloor = 0
toId OnWall = 1
toId OnCeiling = 2
instance Cardinality (Face 'False) where
cardinality = 3
instance FromId (Face 'True) where
fromId 0 = OnFloor
fromId 1 = OnCeiling
fromId 2 = OnSingleWall
fromId 3 = OnDoubleWall
instance ToId (Face 'True) where
toId OnFloor = 0
toId OnCeiling = 1
toId OnSingleWall = 2
toId OnDoubleWall = 3
instance Cardinality (Face 'True) where
cardinality = 4
data SlabType = TopSlab | BottomSlab | DoubleSlab
instance FromId SlabType where
fromId 0 = TopSlab
fromId 1 = BottomSlab
fromId 2 = DoubleSlab
instance ToId SlabType where
toId TopSlab = 0
toId BottomSlab = 1
toId DoubleSlab = 2
instance Cardinality SlabType where
cardinality = 3
data Axis = XAxis | YAxis | ZAxis
instance FromId Axis where
fromId 0 = XAxis
fromId 1 = YAxis
fromId 2 = ZAxis
instance ToId Axis where
toId XAxis = 0
toId YAxis = 1
toId ZAxis = 2
instance Cardinality Axis where
cardinality = 3
newtype GrowthStage (max :: Nat) = GrowthStage Int
instance FromId (GrowthStage max) where
fromId = coerce -- We do no bounds checking here as these values always come from the pattern synonyms, we later only export smart constructors -- TODO Actually do that and add a better note somewhere
instance ToId (GrowthStage max) where
toId = coerce
instance KnownNat max => Cardinality (GrowthStage max) where
cardinality = fromIntegral $ natVal @max undefined + 1
data StairShape = Straight | InnerLeft | InnerRight | OuterLeft | OuterRight
instance FromId StairShape where
fromId 0 = Straight
fromId 1 = InnerLeft
fromId 2 = InnerRight
fromId 3 = OuterLeft
fromId 4 = OuterRight
instance ToId StairShape where
toId Straight = 0
toId InnerLeft = 1
toId InnerRight = 2
toId OuterLeft = 3
toId OuterRight = 4
instance Cardinality StairShape where
cardinality = 5
data Half = TopHalf | BottomHalf
instance FromId Half where
fromId 0 = TopHalf
fromId 1 = BottomHalf
instance ToId Half where
toId TopHalf = 0
toId BottomHalf = 1
instance Cardinality Half where
cardinality = 2
data BedPart = HeadPart | FootPart
instance FromId BedPart where
fromId 0 = HeadPart
fromId 1 = FootPart
instance ToId BedPart where
toId HeadPart = 0
toId FootPart = 1
instance Cardinality BedPart where
cardinality = 2
data Occupied = Occupied | NotOccupied
instance FromId Occupied where
fromId 0 = Occupied
fromId 1 = NotOccupied
instance ToId Occupied where
toId Occupied = 0
toId NotOccupied = 1
instance Cardinality Occupied where
cardinality = 2
data Persistent = Persistent | NotPersistent
instance FromId Persistent where
fromId 0 = Persistent
fromId 1 = NotPersistent
instance ToId Persistent where
toId Persistent = 0
toId NotPersistent = 1
instance Cardinality Persistent where
cardinality = 2
newtype LeafDistance = LeafDistance Int
instance FromId LeafDistance where
fromId n = LeafDistance $ n + 1
instance ToId LeafDistance where
toId (LeafDistance n) = n - 1
instance Cardinality LeafDistance where
cardinality = 7
newtype Age (max :: Nat) = Age Int
instance FromId (Age max) where
fromId = coerce
instance ToId (Age max) where
toId = coerce
instance KnownNat max => Cardinality (Age max) where
cardinality = (fromIntegral $ natVal @max undefined) + 1
newtype HoneyLevel = HoneyLevel Int
instance FromId HoneyLevel where
fromId = coerce
instance ToId HoneyLevel where
toId = coerce
instance Cardinality HoneyLevel where
cardinality = 6
data Lit = Lit | NotLit
instance FromId Lit where
fromId 0 = Lit
fromId 1 = NotLit
instance ToId Lit where
toId Lit = 0
toId NotLit = 1
instance Cardinality Lit where
cardinality = 2
data ChestType = SingleChest | LeftChest | RightChest
instance FromId ChestType where
fromId 0 = SingleChest
fromId 1 = LeftChest
fromId 2 = RightChest
instance ToId ChestType where
toId SingleChest = 0
toId LeftChest = 1
toId RightChest = 2
instance Cardinality ChestType where
cardinality = 3
data Open = Open | Closed
instance FromId Open where
fromId 0 = Open
fromId 1 = Closed
instance ToId Open where
toId Open = 0
toId Closed = 1
instance Cardinality Open where
cardinality = 2
newtype FluidLevel (max :: Nat) = FluidLevel Int
instance FromId (FluidLevel max) where
fromId = coerce
instance ToId (FluidLevel max) where
toId = coerce
instance KnownNat max => Cardinality (FluidLevel max) where
cardinality = (fromIntegral $ natVal @max undefined) + 1
data Conditional = Conditional | NotConditional
instance FromId Conditional where
fromId 0 = Conditional
fromId 1 = NotConditional
instance ToId Conditional where
toId Conditional = 0
toId NotConditional = 1
instance Cardinality Conditional where
cardinality = 2
newtype Candles = Candles Int
instance FromId Candles where
fromId n = Candles $ n + 1
instance ToId Candles where
toId (Candles n) = n - 1
instance Cardinality Candles where
cardinality = 4
data MushroomExposed (side :: Facing 'True 'True) = Exposed | NotExposed
instance FromId (MushroomExposed side) where
fromId 0 = Exposed
fromId 1 = NotExposed
instance ToId (MushroomExposed side) where
toId Exposed = 0
toId NotExposed = 1
instance Cardinality (MushroomExposed s) where
cardinality = 2
data Berries = Berries | NoBerries
instance FromId Berries where
fromId 0 = Berries
fromId 1 = NoBerries
instance ToId Berries where
toId Berries = 0
toId NoBerries = 1
instance Cardinality Berries where
cardinality = 2
data RedstonePlacement (side :: Facing 'False 'False) = RedstoneUp | RedstoneSide | RedstoneNone
instance FromId (RedstonePlacement side) where
fromId 0 = RedstoneUp
fromId 1 = RedstoneSide
fromId 2 = RedstoneNone
instance ToId (RedstonePlacement side) where
toId RedstoneUp = 0
toId RedstoneSide = 1
toId RedstoneNone = 2
instance Cardinality (RedstonePlacement side) where
cardinality = 3
newtype Power = Power Int
instance FromId Power where
fromId = coerce
instance ToId Power where
toId = coerce
instance Cardinality Power where
cardinality = 16
newtype LightLevel = LightLevel Int
instance FromId LightLevel where
fromId = coerce
instance ToId LightLevel where
toId = coerce
instance Cardinality LightLevel where
cardinality = 16
data HingeSide = HingeLeft | HingeRight
instance FromId HingeSide where
fromId 0 = HingeLeft
fromId 1 = HingeRight
instance ToId HingeSide where
toId HingeLeft = 0
toId HingeRight = 1
instance Cardinality HingeSide where
cardinality = 2
newtype CauldronFill = CauldronFill Int
instance FromId CauldronFill where
fromId n = CauldronFill $ n + 1
instance ToId CauldronFill where
toId (CauldronFill fill) = fill -1
instance Cardinality CauldronFill where
cardinality = 3
data Snowy = Snowy | NotSnowy
instance FromId Snowy where
fromId 0 = Snowy
fromId 1 = NotSnowy
instance ToId Snowy where
toId Snowy = 0
toId NotSnowy = 1
instance Cardinality Snowy where
cardinality = 2
data SculkSensorPhase = SensorInactive | SensorActive | SensorOnCooldown
instance FromId SculkSensorPhase where
fromId 0 = SensorInactive
fromId 1 = SensorActive
fromId 2 = SensorOnCooldown
instance ToId SculkSensorPhase where
toId SensorInactive = 0
toId SensorActive = 1
toId SensorOnCooldown = 2
instance Cardinality SculkSensorPhase where
cardinality = 3
newtype Rotation = Rotation Int
instance FromId Rotation where
fromId = coerce
instance ToId Rotation where
toId = coerce
instance Cardinality Rotation where
cardinality = 16
data FenceGateInWall = InWall | NotInWall
instance FromId FenceGateInWall where
fromId 0 = InWall
fromId 1 = NotInWall
instance ToId FenceGateInWall where
toId InWall = 0
toId NotInWall = 1
instance Cardinality FenceGateInWall where
cardinality = 2
data HasBottle (nr :: Nat) = HasBottle | HasNoBottle
instance FromId (HasBottle nr) where
fromId 0 = HasBottle
fromId 1 = HasNoBottle
instance ToId (HasBottle nr) where
toId HasBottle = 0
toId HasNoBottle = 1
instance Cardinality (HasBottle nr) where
cardinality = 2
data TnTStable = TnTStable | TnTUnstable
instance FromId TnTStable where
fromId 0 = TnTUnstable
fromId 1 = TnTStable
instance ToId TnTStable where
toId TnTStable = 1
toId TnTUnstable = 0
instance Cardinality TnTStable where
cardinality = 2
data VerticalDirection = DirUp | DirDown
instance FromId VerticalDirection where
fromId 0 = DirUp
fromId 1 = DirDown
instance ToId VerticalDirection where
toId DirUp = 0
toId DirDown = 1
instance Cardinality VerticalDirection where
cardinality = 2
data DripstoneThickness = TipMerge | Tip | Frustum | Middle | Base
instance FromId DripstoneThickness where
fromId 0 = TipMerge
fromId 1 = Tip
fromId 2 = Frustum
fromId 3 = Middle
fromId 4 = Base
instance ToId DripstoneThickness where
toId TipMerge = 0
toId Tip = 1
toId Frustum = 2
toId Middle = 3
toId Base = 4
instance Cardinality DripstoneThickness where
cardinality = 5
data HasRecord = HasRecord | HasNoRecord
instance FromId HasRecord where
fromId 0 = HasRecord
fromId 1 = HasNoRecord
instance ToId HasRecord where
toId HasRecord = 0
toId HasNoRecord = 1
instance Cardinality HasRecord where
cardinality = 2
data Orientation where
DownEast :: Orientation
DownNorth :: Orientation
DownSouth :: Orientation
DownWest :: Orientation
UpEast :: Orientation
UpNorth :: Orientation
UpSouth :: Orientation
UpWest :: Orientation
WestUp :: Orientation
EastUp :: Orientation
NorthUp :: Orientation
SouthUp :: Orientation
instance FromId Orientation where
fromId 0 = DownEast
fromId 1 = DownNorth
fromId 2 = DownSouth
fromId 3 = DownWest
fromId 4 = UpEast
fromId 5 = UpNorth
fromId 6 = UpSouth
fromId 7 = UpWest
fromId 8 = WestUp
fromId 9 = EastUp
fromId 10 = NorthUp
fromId 11 = SouthUp
instance ToId Orientation where
toId DownEast = 0
toId DownNorth = 1
toId DownSouth = 2
toId DownWest = 3
toId UpEast = 4
toId UpNorth = 5
toId UpSouth = 6
toId UpWest = 7
toId WestUp = 8
toId EastUp = 9
toId NorthUp = 10
toId SouthUp = 11
instance Cardinality Orientation where
cardinality = 12
newtype ComposterFill = ComposterFill Int
instance FromId ComposterFill where
fromId = coerce
instance ToId ComposterFill where
toId = coerce
instance Cardinality ComposterFill where
cardinality = 9
data Locked = Locked | Unlocked
instance FromId Locked where
fromId 0 = Locked
fromId 1 = Unlocked
instance ToId Locked where
toId Locked = 0
toId Unlocked = 1
instance Cardinality Locked where
cardinality = 2
newtype Delay = Delay Int
instance FromId Delay where
fromId n = Delay $ n + 1
instance ToId Delay where
toId (Delay n) = n - 1
instance Cardinality Delay where
cardinality = 4
data Triggered = Triggered | NotTriggered
instance FromId Triggered where
fromId 0 = Triggered
fromId 1 = NotTriggered
instance ToId Triggered where
toId Triggered = 0
toId NotTriggered = 1
instance Cardinality Triggered where
cardinality = 2
data HasEye = HasEye | HasNoEye
instance FromId HasEye where
fromId 0 = HasEye
fromId 1 = HasNoEye
instance ToId HasEye where
toId HasEye = 0
toId HasNoEye = 1
instance Cardinality HasEye where
cardinality = 2
data Inverted = Inverted | NotInverted
instance FromId Inverted where
fromId 0 = Inverted
fromId 1 = NotInverted
instance ToId Inverted where
toId Inverted = 0
toId NotInverted = 1
instance Cardinality Inverted where
cardinality = 2
data StructureBlockMode = SaveStructure | LoadStructure | CornerStructure | DataStructure
instance FromId StructureBlockMode where
fromId 0 = SaveStructure
fromId 1 = LoadStructure
fromId 2 = CornerStructure
fromId 3 = DataStructure
instance ToId StructureBlockMode where
toId SaveStructure = 0
toId LoadStructure = 1
toId CornerStructure = 2
toId DataStructure = 3
instance Cardinality StructureBlockMode where
cardinality = 4
data Enabled = Enabled | Disabled
instance FromId Enabled where
fromId 0 = Enabled
fromId 1 = Disabled
instance ToId Enabled where
toId Enabled = 0
toId Disabled = 1
instance Cardinality Enabled where
cardinality = 2
data PistonType = Normal | Sticky
instance FromId PistonType where
fromId 0 = Normal
fromId 1 = Sticky
instance ToId PistonType where
toId Normal = 0
toId Sticky = 1
instance Cardinality PistonType where
cardinality = 2
data Short = Short | Long
instance FromId Short where
fromId 0 = Short
fromId 1 = Long
instance ToId Short where
toId Short = 0
toId Long = 1
instance Cardinality Short where
cardinality = 2
data Extended = Extended | Retracted
instance FromId Extended where
fromId 0 = Extended
fromId 1 = Retracted
instance ToId Extended where
toId Extended = 0
toId Retracted = 1
instance Cardinality Extended where
cardinality = 2
data Hanging = Hanging | NotHanging
instance FromId Hanging where
fromId 0 = Hanging
fromId 1 = NotHanging
instance ToId Hanging where
toId Hanging = 0
toId NotHanging = 1
instance Cardinality Hanging where
cardinality = 2
newtype Charges = Charges Int
instance FromId Charges where
fromId = coerce
instance ToId Charges where
toId = coerce
instance Cardinality Charges where
cardinality = 5
data Bottom = Bottom | NoBottom
instance FromId Bottom where
fromId 0 = Bottom
fromId 1 = NoBottom
instance ToId Bottom where
toId Bottom = 0
toId NoBottom = 1
instance Cardinality Bottom where
cardinality = 2
newtype Pickles = Pickles Int
instance FromId Pickles where
fromId n = Pickles $ n + 1
instance ToId Pickles where
toId (Pickles n) = n - 1
instance Cardinality Pickles where
cardinality = 4
newtype SnowLayers = SnowLayers Int
instance FromId SnowLayers where
fromId n = SnowLayers $ n + 1
instance ToId SnowLayers where
toId (SnowLayers n) = n - 1
instance Cardinality SnowLayers where
cardinality = 8
newtype Bites = Bites Int
instance FromId Bites where
fromId = coerce
instance ToId Bites where
toId = coerce
instance Cardinality Bites where
cardinality = 7
data Drag = Drag | NoDrag
instance FromId Drag where
fromId 0 = Drag
fromId 1 = NoDrag
instance ToId Drag where
toId Drag = 0
toId NoDrag = 1
instance Cardinality Drag where
cardinality = 2
data BambooLeaves = NoLeaves | SmallLeaves | LargeLeaves
instance FromId BambooLeaves where
fromId 0 = NoLeaves
fromId 1 = SmallLeaves
fromId 2 = LargeLeaves
instance ToId BambooLeaves where
toId NoLeaves = 0
toId SmallLeaves = 1
toId LargeLeaves = 2
instance Cardinality BambooLeaves where
cardinality = 3
data SignalFire = SignalFire | NoSignalFire
instance FromId SignalFire where
fromId 0 = SignalFire
fromId 1 = NoSignalFire
instance ToId SignalFire where
toId SignalFire = 0
toId NoSignalFire = 1
instance Cardinality SignalFire where
cardinality = 2
data HasBook = HasBook | HasNoBook
instance FromId HasBook where
fromId 0 = HasBook
fromId 1 = HasNoBook
instance ToId HasBook where
toId HasBook = 0
toId HasNoBook = 1
instance Cardinality HasBook where
cardinality = 2
newtype Eggs = Eggs Int
instance FromId Eggs where
fromId n = Eggs $ n + 1
instance ToId Eggs where
toId (Eggs n) = n - 1
instance Cardinality Eggs where
cardinality = 4
newtype Hatch = Hatch Int
instance FromId Hatch where
fromId = coerce
instance ToId Hatch where
toId = coerce
instance Cardinality Hatch where
cardinality = 3
data WireAttached = WireAttached | WireDetached
instance FromId WireAttached where
fromId 0 = WireAttached
fromId 1 = WireDetached
instance ToId WireAttached where
toId WireAttached = 0
toId WireDetached = 1
instance Cardinality WireAttached where
cardinality = 2
data Tilt = NoTilt | UnstableTilt | PartialTilt | FullTilt
instance FromId Tilt where
fromId 0 = NoTilt
fromId 1 = UnstableTilt
fromId 2 = PartialTilt
fromId 3 = FullTilt
instance ToId Tilt where
toId NoTilt = 0
toId UnstableTilt = 1
toId PartialTilt = 2
toId FullTilt = 3
instance Cardinality Tilt where
cardinality = 4
newtype Note = Note Int
instance FromId Note where
fromId = coerce
instance ToId Note where
toId = coerce
instance Cardinality Note where
cardinality = 25
data Instrument =
Harp | Basedrum | Snare | Hat | Bass | Flute | InstrumentBell | Guitar | Chime
| Xylophone | IronXylophone | Cowbell | Didgeridoo | Bit | Banjo | Pling
instance FromId Instrument where
fromId 0 = Harp
fromId 1 = Basedrum
fromId 2 = Snare
fromId 3 = Hat
fromId 4 = Bass
fromId 5 = Flute
fromId 6 = InstrumentBell
fromId 7 = Guitar
fromId 8 = Chime
fromId 9 = Xylophone
fromId 10 = IronXylophone
fromId 11 = Cowbell
fromId 12 = Didgeridoo
fromId 13 = Bit
fromId 14 = Banjo
fromId 15 = Pling
instance ToId Instrument where
toId Harp = 0
toId Basedrum = 1
toId Snare = 2
toId Hat = 3
toId Bass = 4
toId Flute = 5
toId InstrumentBell = 6
toId Guitar = 7
toId Chime = 8
toId Xylophone = 9
toId IronXylophone = 10
toId Cowbell = 11
toId Didgeridoo = 12
toId Bit = 13
toId Banjo = 14
toId Pling = 15
instance Cardinality Instrument where
cardinality = 16
data Disarmed = Disarmed | Armed
instance FromId Disarmed where
fromId 0 = Disarmed
fromId 1 = Armed
instance ToId Disarmed where
toId Disarmed = 0
toId Armed = 1
instance Cardinality Disarmed where
cardinality = 2
newtype Moisture = Moisture Int
instance FromId Moisture where
fromId = coerce
instance ToId Moisture where
toId = coerce
instance Cardinality Moisture where
cardinality = 7
data SlotOccupied (n :: Nat) = SlotOccupied | SlotEmpty
instance FromId (SlotOccupied n) where
fromId 0 = SlotEmpty
fromId 1 = SlotOccupied
instance ToId (SlotOccupied n) where
toId SlotEmpty = 0
toId SlotOccupied = 1
instance Cardinality (SlotOccupied n) where
cardinality = 2
data Bloom = Bloom | NoBloom
instance FromId Bloom where
fromId 0 = NoBloom
fromId 1 = Bloom
instance ToId Bloom where
toId NoBloom = 0
toId Bloom = 1
instance Cardinality Bloom where
cardinality = 2
data CanSummon = CanSummon | CannotSummon
instance FromId CanSummon where
fromId 0 = CannotSummon
fromId 1 = CanSummon
instance ToId CanSummon where
toId CannotSummon = 0
toId CanSummon = 1
instance Cardinality CanSummon where
cardinality = 2
data Shrieking = Shrieking | NotShrieking
instance FromId Shrieking where
fromId 0 = NotShrieking
fromId 1 = Shrieking
instance ToId Shrieking where
toId NotShrieking = 0
toId Shrieking = 1
instance Cardinality Shrieking where
cardinality = 2
inRange :: Int -> Int -> Int -> Bool
inRange x y z | y == z - 1 = x == y
| otherwise = y <= x && x < z
# INLINE inRange #
generateBlockStatePatterns
| null | https://raw.githubusercontent.com/1Jajen1/Brokkr/1c93519fdc3490091205e8499ed04cd1fee66192/data/src/Block/Internal/BlockState.hs | haskell | # LANGUAGE GADTs #
{-# OPTIONS_GHC -ddump-simpl -dsuppress-all #-}
TODO Generate better show instance
Aux types TODO Autogen some of these. Especially the boolean equivalents
Or at least autogent the instances, that should not be hard!
We do no bounds checking here as these values always come from the pattern synonyms, we later only export smart constructors -- TODO Actually do that and add a better note somewhere | # LANGUAGE TemplateHaskell #
# LANGUAGE PatternSynonyms #
# LANGUAGE ViewPatterns #
# LANGUAGE AllowAmbiguousTypes #
# LANGUAGE DataKinds #
# OPTIONS_GHC -Wno - incomplete - patterns -Wno - missing - export - lists -Wno - unused - local - binds #
module Block.Internal.BlockState where
import Block.Internal.TH
import Data.Coerce
import GHC.TypeLits
newtype BlockState = BlockState Int
class ToId a where
toId :: a -> Int
class FromId a where
fromId :: Int -> a
class Cardinality a where
cardinality :: Int
data Facing (up :: Bool) (down :: Bool) where
North :: Facing up down
East :: Facing up down
South :: Facing up down
West :: Facing up down
Up :: Facing 'True down
Down :: Facing up 'True
deriving stock instance Show (Facing 'True 'True )
deriving stock instance Show (Facing 'False 'False)
deriving stock instance Show (Facing 'False 'True )
deriving stock instance Show (Facing 'True 'False)
deriving stock instance Eq (Facing 'True 'True )
deriving stock instance Eq (Facing 'False 'False)
deriving stock instance Eq (Facing 'False 'True )
deriving stock instance Eq (Facing 'True 'False)
instance FromId (Facing 'False 'False) where
fromId 0 = North
fromId 1 = South
fromId 2 = West
fromId 3 = East
instance FromId (Facing 'True 'True) where
fromId 0 = North
fromId 1 = South
fromId 2 = West
fromId 3 = East
fromId 4 = Up
fromId 5 = Down
instance FromId (Facing 'False 'True) where
fromId 0 = Down
fromId 1 = North
fromId 2 = South
fromId 3 = West
fromId 4 = East
instance ToId (Facing 'False 'False) where
toId North = 0
toId East = 1
toId South = 2
toId West = 3
instance ToId (Facing 'True 'True) where
toId North = 0
toId East = 1
toId South = 2
toId West = 3
toId Up = 4
toId Down = 5
instance ToId (Facing 'False 'True) where
toId North = 1
toId East = 2
toId South = 3
toId West = 4
toId Down = 0
instance Cardinality (Facing 'False 'False) where
cardinality = 4
instance Cardinality (Facing 'True 'False) where
cardinality = 5
instance Cardinality (Facing 'False 'True) where
cardinality = 5
instance Cardinality (Facing 'True 'True) where
cardinality = 6
data Attached (up :: Bool) (down :: Bool) (side :: Facing up down) = Attached | NotAttached
instance FromId (Attached up down side) where
fromId 0 = Attached
fromId 1 = NotAttached
instance ToId (Attached up down side) where
toId Attached = 0
toId NotAttached = 1
instance Cardinality (Attached up down side) where
cardinality = 2
data WallAttached (side :: Facing 'False 'False) = Low | Tall | None
instance FromId (WallAttached side) where
fromId 0 = None
fromId 1 = Low
fromId 2 = Tall
instance ToId (WallAttached side) where
toId None = 0
toId Low = 1
toId Tall = 2
instance Cardinality (WallAttached s) where
cardinality = 3
data Waterlogged = Waterlogged | NotWaterlogged
instance FromId Waterlogged where
fromId 0 = Waterlogged
fromId 1 = NotWaterlogged
instance ToId Waterlogged where
toId Waterlogged = 0
toId NotWaterlogged = 1
instance Cardinality Waterlogged where
cardinality = 2
data Powered = Powered | NotPowered
instance FromId Powered where
fromId 0 = Powered
fromId 1 = NotPowered
instance ToId Powered where
toId Powered = 0
toId NotPowered = 1
instance Cardinality Powered where
cardinality = 2
data Face (bell :: Bool) where
OnFloor :: Face bell
OnWall :: Face 'False
OnCeiling :: Face bell
OnSingleWall :: Face 'True
OnDoubleWall :: Face 'True
instance FromId (Face 'False) where
fromId 0 = OnFloor
fromId 1 = OnWall
fromId 2 = OnCeiling
instance ToId (Face 'False) where
toId OnFloor = 0
toId OnWall = 1
toId OnCeiling = 2
instance Cardinality (Face 'False) where
cardinality = 3
instance FromId (Face 'True) where
fromId 0 = OnFloor
fromId 1 = OnCeiling
fromId 2 = OnSingleWall
fromId 3 = OnDoubleWall
instance ToId (Face 'True) where
toId OnFloor = 0
toId OnCeiling = 1
toId OnSingleWall = 2
toId OnDoubleWall = 3
instance Cardinality (Face 'True) where
cardinality = 4
data SlabType = TopSlab | BottomSlab | DoubleSlab
instance FromId SlabType where
fromId 0 = TopSlab
fromId 1 = BottomSlab
fromId 2 = DoubleSlab
instance ToId SlabType where
toId TopSlab = 0
toId BottomSlab = 1
toId DoubleSlab = 2
instance Cardinality SlabType where
cardinality = 3
data Axis = XAxis | YAxis | ZAxis
instance FromId Axis where
fromId 0 = XAxis
fromId 1 = YAxis
fromId 2 = ZAxis
instance ToId Axis where
toId XAxis = 0
toId YAxis = 1
toId ZAxis = 2
instance Cardinality Axis where
cardinality = 3
newtype GrowthStage (max :: Nat) = GrowthStage Int
instance FromId (GrowthStage max) where
instance ToId (GrowthStage max) where
toId = coerce
instance KnownNat max => Cardinality (GrowthStage max) where
cardinality = fromIntegral $ natVal @max undefined + 1
data StairShape = Straight | InnerLeft | InnerRight | OuterLeft | OuterRight
instance FromId StairShape where
fromId 0 = Straight
fromId 1 = InnerLeft
fromId 2 = InnerRight
fromId 3 = OuterLeft
fromId 4 = OuterRight
instance ToId StairShape where
toId Straight = 0
toId InnerLeft = 1
toId InnerRight = 2
toId OuterLeft = 3
toId OuterRight = 4
instance Cardinality StairShape where
cardinality = 5
data Half = TopHalf | BottomHalf
instance FromId Half where
fromId 0 = TopHalf
fromId 1 = BottomHalf
instance ToId Half where
toId TopHalf = 0
toId BottomHalf = 1
instance Cardinality Half where
cardinality = 2
data BedPart = HeadPart | FootPart
instance FromId BedPart where
fromId 0 = HeadPart
fromId 1 = FootPart
instance ToId BedPart where
toId HeadPart = 0
toId FootPart = 1
instance Cardinality BedPart where
cardinality = 2
data Occupied = Occupied | NotOccupied
instance FromId Occupied where
fromId 0 = Occupied
fromId 1 = NotOccupied
instance ToId Occupied where
toId Occupied = 0
toId NotOccupied = 1
instance Cardinality Occupied where
cardinality = 2
data Persistent = Persistent | NotPersistent
instance FromId Persistent where
fromId 0 = Persistent
fromId 1 = NotPersistent
instance ToId Persistent where
toId Persistent = 0
toId NotPersistent = 1
instance Cardinality Persistent where
cardinality = 2
newtype LeafDistance = LeafDistance Int
instance FromId LeafDistance where
fromId n = LeafDistance $ n + 1
instance ToId LeafDistance where
toId (LeafDistance n) = n - 1
instance Cardinality LeafDistance where
cardinality = 7
newtype Age (max :: Nat) = Age Int
instance FromId (Age max) where
fromId = coerce
instance ToId (Age max) where
toId = coerce
instance KnownNat max => Cardinality (Age max) where
cardinality = (fromIntegral $ natVal @max undefined) + 1
newtype HoneyLevel = HoneyLevel Int
instance FromId HoneyLevel where
fromId = coerce
instance ToId HoneyLevel where
toId = coerce
instance Cardinality HoneyLevel where
cardinality = 6
data Lit = Lit | NotLit
instance FromId Lit where
fromId 0 = Lit
fromId 1 = NotLit
instance ToId Lit where
toId Lit = 0
toId NotLit = 1
instance Cardinality Lit where
cardinality = 2
data ChestType = SingleChest | LeftChest | RightChest
instance FromId ChestType where
fromId 0 = SingleChest
fromId 1 = LeftChest
fromId 2 = RightChest
instance ToId ChestType where
toId SingleChest = 0
toId LeftChest = 1
toId RightChest = 2
instance Cardinality ChestType where
cardinality = 3
data Open = Open | Closed
instance FromId Open where
fromId 0 = Open
fromId 1 = Closed
instance ToId Open where
toId Open = 0
toId Closed = 1
instance Cardinality Open where
cardinality = 2
newtype FluidLevel (max :: Nat) = FluidLevel Int
instance FromId (FluidLevel max) where
fromId = coerce
instance ToId (FluidLevel max) where
toId = coerce
instance KnownNat max => Cardinality (FluidLevel max) where
cardinality = (fromIntegral $ natVal @max undefined) + 1
data Conditional = Conditional | NotConditional
instance FromId Conditional where
fromId 0 = Conditional
fromId 1 = NotConditional
instance ToId Conditional where
toId Conditional = 0
toId NotConditional = 1
instance Cardinality Conditional where
cardinality = 2
newtype Candles = Candles Int
instance FromId Candles where
fromId n = Candles $ n + 1
instance ToId Candles where
toId (Candles n) = n - 1
instance Cardinality Candles where
cardinality = 4
data MushroomExposed (side :: Facing 'True 'True) = Exposed | NotExposed
instance FromId (MushroomExposed side) where
fromId 0 = Exposed
fromId 1 = NotExposed
instance ToId (MushroomExposed side) where
toId Exposed = 0
toId NotExposed = 1
instance Cardinality (MushroomExposed s) where
cardinality = 2
data Berries = Berries | NoBerries
instance FromId Berries where
fromId 0 = Berries
fromId 1 = NoBerries
instance ToId Berries where
toId Berries = 0
toId NoBerries = 1
instance Cardinality Berries where
cardinality = 2
data RedstonePlacement (side :: Facing 'False 'False) = RedstoneUp | RedstoneSide | RedstoneNone
instance FromId (RedstonePlacement side) where
fromId 0 = RedstoneUp
fromId 1 = RedstoneSide
fromId 2 = RedstoneNone
instance ToId (RedstonePlacement side) where
toId RedstoneUp = 0
toId RedstoneSide = 1
toId RedstoneNone = 2
instance Cardinality (RedstonePlacement side) where
cardinality = 3
newtype Power = Power Int
instance FromId Power where
fromId = coerce
instance ToId Power where
toId = coerce
instance Cardinality Power where
cardinality = 16
newtype LightLevel = LightLevel Int
instance FromId LightLevel where
fromId = coerce
instance ToId LightLevel where
toId = coerce
instance Cardinality LightLevel where
cardinality = 16
data HingeSide = HingeLeft | HingeRight
instance FromId HingeSide where
fromId 0 = HingeLeft
fromId 1 = HingeRight
instance ToId HingeSide where
toId HingeLeft = 0
toId HingeRight = 1
instance Cardinality HingeSide where
cardinality = 2
newtype CauldronFill = CauldronFill Int
instance FromId CauldronFill where
fromId n = CauldronFill $ n + 1
instance ToId CauldronFill where
toId (CauldronFill fill) = fill -1
instance Cardinality CauldronFill where
cardinality = 3
data Snowy = Snowy | NotSnowy
instance FromId Snowy where
fromId 0 = Snowy
fromId 1 = NotSnowy
instance ToId Snowy where
toId Snowy = 0
toId NotSnowy = 1
instance Cardinality Snowy where
cardinality = 2
data SculkSensorPhase = SensorInactive | SensorActive | SensorOnCooldown
instance FromId SculkSensorPhase where
fromId 0 = SensorInactive
fromId 1 = SensorActive
fromId 2 = SensorOnCooldown
instance ToId SculkSensorPhase where
toId SensorInactive = 0
toId SensorActive = 1
toId SensorOnCooldown = 2
instance Cardinality SculkSensorPhase where
cardinality = 3
newtype Rotation = Rotation Int
instance FromId Rotation where
fromId = coerce
instance ToId Rotation where
toId = coerce
instance Cardinality Rotation where
cardinality = 16
data FenceGateInWall = InWall | NotInWall
instance FromId FenceGateInWall where
fromId 0 = InWall
fromId 1 = NotInWall
instance ToId FenceGateInWall where
toId InWall = 0
toId NotInWall = 1
instance Cardinality FenceGateInWall where
cardinality = 2
data HasBottle (nr :: Nat) = HasBottle | HasNoBottle
instance FromId (HasBottle nr) where
fromId 0 = HasBottle
fromId 1 = HasNoBottle
instance ToId (HasBottle nr) where
toId HasBottle = 0
toId HasNoBottle = 1
instance Cardinality (HasBottle nr) where
cardinality = 2
data TnTStable = TnTStable | TnTUnstable
instance FromId TnTStable where
fromId 0 = TnTUnstable
fromId 1 = TnTStable
instance ToId TnTStable where
toId TnTStable = 1
toId TnTUnstable = 0
instance Cardinality TnTStable where
cardinality = 2
data VerticalDirection = DirUp | DirDown
instance FromId VerticalDirection where
fromId 0 = DirUp
fromId 1 = DirDown
instance ToId VerticalDirection where
toId DirUp = 0
toId DirDown = 1
instance Cardinality VerticalDirection where
cardinality = 2
data DripstoneThickness = TipMerge | Tip | Frustum | Middle | Base
instance FromId DripstoneThickness where
fromId 0 = TipMerge
fromId 1 = Tip
fromId 2 = Frustum
fromId 3 = Middle
fromId 4 = Base
instance ToId DripstoneThickness where
toId TipMerge = 0
toId Tip = 1
toId Frustum = 2
toId Middle = 3
toId Base = 4
instance Cardinality DripstoneThickness where
cardinality = 5
data HasRecord = HasRecord | HasNoRecord
instance FromId HasRecord where
fromId 0 = HasRecord
fromId 1 = HasNoRecord
instance ToId HasRecord where
toId HasRecord = 0
toId HasNoRecord = 1
instance Cardinality HasRecord where
cardinality = 2
data Orientation where
DownEast :: Orientation
DownNorth :: Orientation
DownSouth :: Orientation
DownWest :: Orientation
UpEast :: Orientation
UpNorth :: Orientation
UpSouth :: Orientation
UpWest :: Orientation
WestUp :: Orientation
EastUp :: Orientation
NorthUp :: Orientation
SouthUp :: Orientation
instance FromId Orientation where
fromId 0 = DownEast
fromId 1 = DownNorth
fromId 2 = DownSouth
fromId 3 = DownWest
fromId 4 = UpEast
fromId 5 = UpNorth
fromId 6 = UpSouth
fromId 7 = UpWest
fromId 8 = WestUp
fromId 9 = EastUp
fromId 10 = NorthUp
fromId 11 = SouthUp
instance ToId Orientation where
toId DownEast = 0
toId DownNorth = 1
toId DownSouth = 2
toId DownWest = 3
toId UpEast = 4
toId UpNorth = 5
toId UpSouth = 6
toId UpWest = 7
toId WestUp = 8
toId EastUp = 9
toId NorthUp = 10
toId SouthUp = 11
instance Cardinality Orientation where
cardinality = 12
newtype ComposterFill = ComposterFill Int
instance FromId ComposterFill where
fromId = coerce
instance ToId ComposterFill where
toId = coerce
instance Cardinality ComposterFill where
cardinality = 9
data Locked = Locked | Unlocked
instance FromId Locked where
fromId 0 = Locked
fromId 1 = Unlocked
instance ToId Locked where
toId Locked = 0
toId Unlocked = 1
instance Cardinality Locked where
cardinality = 2
newtype Delay = Delay Int
instance FromId Delay where
fromId n = Delay $ n + 1
instance ToId Delay where
toId (Delay n) = n - 1
instance Cardinality Delay where
cardinality = 4
data Triggered = Triggered | NotTriggered
instance FromId Triggered where
fromId 0 = Triggered
fromId 1 = NotTriggered
instance ToId Triggered where
toId Triggered = 0
toId NotTriggered = 1
instance Cardinality Triggered where
cardinality = 2
data HasEye = HasEye | HasNoEye
instance FromId HasEye where
fromId 0 = HasEye
fromId 1 = HasNoEye
instance ToId HasEye where
toId HasEye = 0
toId HasNoEye = 1
instance Cardinality HasEye where
cardinality = 2
data Inverted = Inverted | NotInverted
instance FromId Inverted where
fromId 0 = Inverted
fromId 1 = NotInverted
instance ToId Inverted where
toId Inverted = 0
toId NotInverted = 1
instance Cardinality Inverted where
cardinality = 2
data StructureBlockMode = SaveStructure | LoadStructure | CornerStructure | DataStructure
instance FromId StructureBlockMode where
fromId 0 = SaveStructure
fromId 1 = LoadStructure
fromId 2 = CornerStructure
fromId 3 = DataStructure
instance ToId StructureBlockMode where
toId SaveStructure = 0
toId LoadStructure = 1
toId CornerStructure = 2
toId DataStructure = 3
instance Cardinality StructureBlockMode where
cardinality = 4
data Enabled = Enabled | Disabled
instance FromId Enabled where
fromId 0 = Enabled
fromId 1 = Disabled
instance ToId Enabled where
toId Enabled = 0
toId Disabled = 1
instance Cardinality Enabled where
cardinality = 2
data PistonType = Normal | Sticky
instance FromId PistonType where
fromId 0 = Normal
fromId 1 = Sticky
instance ToId PistonType where
toId Normal = 0
toId Sticky = 1
instance Cardinality PistonType where
cardinality = 2
data Short = Short | Long
instance FromId Short where
fromId 0 = Short
fromId 1 = Long
instance ToId Short where
toId Short = 0
toId Long = 1
instance Cardinality Short where
cardinality = 2
data Extended = Extended | Retracted
instance FromId Extended where
fromId 0 = Extended
fromId 1 = Retracted
instance ToId Extended where
toId Extended = 0
toId Retracted = 1
instance Cardinality Extended where
cardinality = 2
data Hanging = Hanging | NotHanging
instance FromId Hanging where
fromId 0 = Hanging
fromId 1 = NotHanging
instance ToId Hanging where
toId Hanging = 0
toId NotHanging = 1
instance Cardinality Hanging where
cardinality = 2
newtype Charges = Charges Int
instance FromId Charges where
fromId = coerce
instance ToId Charges where
toId = coerce
instance Cardinality Charges where
cardinality = 5
data Bottom = Bottom | NoBottom
instance FromId Bottom where
fromId 0 = Bottom
fromId 1 = NoBottom
instance ToId Bottom where
toId Bottom = 0
toId NoBottom = 1
instance Cardinality Bottom where
cardinality = 2
newtype Pickles = Pickles Int
instance FromId Pickles where
fromId n = Pickles $ n + 1
instance ToId Pickles where
toId (Pickles n) = n - 1
instance Cardinality Pickles where
cardinality = 4
newtype SnowLayers = SnowLayers Int
instance FromId SnowLayers where
fromId n = SnowLayers $ n + 1
instance ToId SnowLayers where
toId (SnowLayers n) = n - 1
instance Cardinality SnowLayers where
cardinality = 8
newtype Bites = Bites Int
instance FromId Bites where
fromId = coerce
instance ToId Bites where
toId = coerce
instance Cardinality Bites where
cardinality = 7
data Drag = Drag | NoDrag
instance FromId Drag where
fromId 0 = Drag
fromId 1 = NoDrag
instance ToId Drag where
toId Drag = 0
toId NoDrag = 1
instance Cardinality Drag where
cardinality = 2
data BambooLeaves = NoLeaves | SmallLeaves | LargeLeaves
instance FromId BambooLeaves where
fromId 0 = NoLeaves
fromId 1 = SmallLeaves
fromId 2 = LargeLeaves
instance ToId BambooLeaves where
toId NoLeaves = 0
toId SmallLeaves = 1
toId LargeLeaves = 2
instance Cardinality BambooLeaves where
cardinality = 3
data SignalFire = SignalFire | NoSignalFire
instance FromId SignalFire where
fromId 0 = SignalFire
fromId 1 = NoSignalFire
instance ToId SignalFire where
toId SignalFire = 0
toId NoSignalFire = 1
instance Cardinality SignalFire where
cardinality = 2
data HasBook = HasBook | HasNoBook
instance FromId HasBook where
fromId 0 = HasBook
fromId 1 = HasNoBook
instance ToId HasBook where
toId HasBook = 0
toId HasNoBook = 1
instance Cardinality HasBook where
cardinality = 2
newtype Eggs = Eggs Int
instance FromId Eggs where
fromId n = Eggs $ n + 1
instance ToId Eggs where
toId (Eggs n) = n - 1
instance Cardinality Eggs where
cardinality = 4
newtype Hatch = Hatch Int
instance FromId Hatch where
fromId = coerce
instance ToId Hatch where
toId = coerce
instance Cardinality Hatch where
cardinality = 3
data WireAttached = WireAttached | WireDetached
instance FromId WireAttached where
fromId 0 = WireAttached
fromId 1 = WireDetached
instance ToId WireAttached where
toId WireAttached = 0
toId WireDetached = 1
instance Cardinality WireAttached where
cardinality = 2
data Tilt = NoTilt | UnstableTilt | PartialTilt | FullTilt
instance FromId Tilt where
fromId 0 = NoTilt
fromId 1 = UnstableTilt
fromId 2 = PartialTilt
fromId 3 = FullTilt
instance ToId Tilt where
toId NoTilt = 0
toId UnstableTilt = 1
toId PartialTilt = 2
toId FullTilt = 3
instance Cardinality Tilt where
cardinality = 4
newtype Note = Note Int
instance FromId Note where
fromId = coerce
instance ToId Note where
toId = coerce
instance Cardinality Note where
cardinality = 25
data Instrument =
Harp | Basedrum | Snare | Hat | Bass | Flute | InstrumentBell | Guitar | Chime
| Xylophone | IronXylophone | Cowbell | Didgeridoo | Bit | Banjo | Pling
instance FromId Instrument where
fromId 0 = Harp
fromId 1 = Basedrum
fromId 2 = Snare
fromId 3 = Hat
fromId 4 = Bass
fromId 5 = Flute
fromId 6 = InstrumentBell
fromId 7 = Guitar
fromId 8 = Chime
fromId 9 = Xylophone
fromId 10 = IronXylophone
fromId 11 = Cowbell
fromId 12 = Didgeridoo
fromId 13 = Bit
fromId 14 = Banjo
fromId 15 = Pling
instance ToId Instrument where
toId Harp = 0
toId Basedrum = 1
toId Snare = 2
toId Hat = 3
toId Bass = 4
toId Flute = 5
toId InstrumentBell = 6
toId Guitar = 7
toId Chime = 8
toId Xylophone = 9
toId IronXylophone = 10
toId Cowbell = 11
toId Didgeridoo = 12
toId Bit = 13
toId Banjo = 14
toId Pling = 15
instance Cardinality Instrument where
cardinality = 16
data Disarmed = Disarmed | Armed
instance FromId Disarmed where
fromId 0 = Disarmed
fromId 1 = Armed
instance ToId Disarmed where
toId Disarmed = 0
toId Armed = 1
instance Cardinality Disarmed where
cardinality = 2
newtype Moisture = Moisture Int
instance FromId Moisture where
fromId = coerce
instance ToId Moisture where
toId = coerce
instance Cardinality Moisture where
cardinality = 7
data SlotOccupied (n :: Nat) = SlotOccupied | SlotEmpty
instance FromId (SlotOccupied n) where
fromId 0 = SlotEmpty
fromId 1 = SlotOccupied
instance ToId (SlotOccupied n) where
toId SlotEmpty = 0
toId SlotOccupied = 1
instance Cardinality (SlotOccupied n) where
cardinality = 2
data Bloom = Bloom | NoBloom
instance FromId Bloom where
fromId 0 = NoBloom
fromId 1 = Bloom
instance ToId Bloom where
toId NoBloom = 0
toId Bloom = 1
instance Cardinality Bloom where
cardinality = 2
data CanSummon = CanSummon | CannotSummon
instance FromId CanSummon where
fromId 0 = CannotSummon
fromId 1 = CanSummon
instance ToId CanSummon where
toId CannotSummon = 0
toId CanSummon = 1
instance Cardinality CanSummon where
cardinality = 2
data Shrieking = Shrieking | NotShrieking
instance FromId Shrieking where
fromId 0 = NotShrieking
fromId 1 = Shrieking
instance ToId Shrieking where
toId NotShrieking = 0
toId Shrieking = 1
instance Cardinality Shrieking where
cardinality = 2
inRange :: Int -> Int -> Int -> Bool
inRange x y z | y == z - 1 = x == y
| otherwise = y <= x && x < z
# INLINE inRange #
generateBlockStatePatterns
|
42e6017c3887b368bac757330c32d36d66a29e58a098df0fc965ea6f4eba106c | gfngfn/SATySFi | imageInfo.mli |
open MyUtil
open LengthInterface
type bbox = float * float * float * float
type key
val initialize : unit -> unit
val add_pdf : abs_path -> int -> key
val add_image : abs_path -> key
val get_height_from_width : key -> length -> length
val get_ratio : key -> length -> length -> float * float
val get_xobject_dictionary : Pdf.t -> Pdf.pdfobject
val get_tag : key -> string
val get_color_space : key -> Pdf.pdfobject option
| null | https://raw.githubusercontent.com/gfngfn/SATySFi/9dbd61df0ab05943b3394830c371e927df45251a/src/backend/imageInfo.mli | ocaml |
open MyUtil
open LengthInterface
type bbox = float * float * float * float
type key
val initialize : unit -> unit
val add_pdf : abs_path -> int -> key
val add_image : abs_path -> key
val get_height_from_width : key -> length -> length
val get_ratio : key -> length -> length -> float * float
val get_xobject_dictionary : Pdf.t -> Pdf.pdfobject
val get_tag : key -> string
val get_color_space : key -> Pdf.pdfobject option
| |
369768195670dc9a3c3ae20a9a19dc1692a7d953517169477f39687cc44d6130 | ocaml/opam-file-format | legacy.ml | (* This "program" is used to verify that the library is linkable - see #40 *)
let file = OpamParser.FullPos.file "../opam-file-format.opam"
in Printf.printf "Successfully loaded %s\n" file.OpamParserTypes.FullPos.file_name
| null | https://raw.githubusercontent.com/ocaml/opam-file-format/d99af5e8f3b917770b3c8d29f55d865fcab3b899/tests/legacy/legacy.ml | ocaml | This "program" is used to verify that the library is linkable - see #40 | let file = OpamParser.FullPos.file "../opam-file-format.opam"
in Printf.printf "Successfully loaded %s\n" file.OpamParserTypes.FullPos.file_name
|
a52554cf82bf58cd7b28e49ebd4e3de240074579c06243abb6228645a40d3c54 | project-fifo/vmwebadm | core.cljs | (ns server.core
(:use-macros [clojure.core.match.js :only [match]])
(:use [server.utils :only [clj->js prn-js prn]])
(:require [server.routes :as routes]
[server.http :as http]
[clojure.string :as c.s]
[cljs.nodejs :as node]
[server.storage :as storage]))
(def http
(node/require "http"))
(def url
(node/require "url"))
(defn parse-url [req]
(let [url (.parse url (.-url req) true)
parts (vec (next (js->clj (.split (.-pathname url) "/"))))
[base ext] (c.s/split (last parts) #"\.")
resource (conj
(vec (butlast parts))
base)
return {:parts parts
:resource resource
:method (.-method req)
:headers (js->clj (.-headers req))
:query (if-let [qry (.-query url)]
(js->clj qry)
{})
:ext ext}]
return))
(defn handler [req res]h
(routes/dispatch
(parse-url req)
req
res))
(defn start [& _]
(storage/init)
(let [server (.createServer http handler)
port (get-in @storage/data [:server :port] 80)
host (get-in @storage/data [:server :host] "0.0.0.0")]
(.listen server port host)
(println "Server running at" (str "http://" host ":" port "/"))))
(set! *main-cli-fn* start)
| null | https://raw.githubusercontent.com/project-fifo/vmwebadm/55d83bbc0ac6db8ea1d784c73d91bf4f228fa04a/src/server/core.cljs | clojure | (ns server.core
(:use-macros [clojure.core.match.js :only [match]])
(:use [server.utils :only [clj->js prn-js prn]])
(:require [server.routes :as routes]
[server.http :as http]
[clojure.string :as c.s]
[cljs.nodejs :as node]
[server.storage :as storage]))
(def http
(node/require "http"))
(def url
(node/require "url"))
(defn parse-url [req]
(let [url (.parse url (.-url req) true)
parts (vec (next (js->clj (.split (.-pathname url) "/"))))
[base ext] (c.s/split (last parts) #"\.")
resource (conj
(vec (butlast parts))
base)
return {:parts parts
:resource resource
:method (.-method req)
:headers (js->clj (.-headers req))
:query (if-let [qry (.-query url)]
(js->clj qry)
{})
:ext ext}]
return))
(defn handler [req res]h
(routes/dispatch
(parse-url req)
req
res))
(defn start [& _]
(storage/init)
(let [server (.createServer http handler)
port (get-in @storage/data [:server :port] 80)
host (get-in @storage/data [:server :host] "0.0.0.0")]
(.listen server port host)
(println "Server running at" (str "http://" host ":" port "/"))))
(set! *main-cli-fn* start)
| |
21e7e90208feefe2a9e6b3a717505a4221d8a9637dffb87bfef3cd21077a2d80 | lmdexpr/ocaml_jvm | attribute_info.ml | open Ubytes.Reader
type t_exception =
{ start_pc : U16.t
; end_pc : U16.t
; handler_pc : U16.t
; catch_type : U16.t
}
type t_line_number =
{ start_pc : U16.t
; line_number : U16.t
}
type t_code =
{ max_stack : int
; max_locals : int
; code : int array
; exception_table : t_exception array
}
type t_verification_type_info =
| Top_variable_info
| Integer_variable_info
| Float_variable_info
| Long_variable_info
| Double_variable_info
| Null_variable_info
| UninitializedThis_variable_info
| Object_variable_info of U16.t
| Uninitialized_variable_info of U16.t
let verification_type_info_to_string = function
| Top_variable_info -> "Top_variable_info"
| Integer_variable_info -> "Integer_variable_info"
| Float_variable_info -> "Float_variable_info"
| Long_variable_info -> "Long_variable_info"
| Double_variable_info -> "Double_variable_info"
| Null_variable_info -> "Null_variable_info"
| UninitializedThis_variable_info -> "UninitializedThis_variable_info"
| Object_variable_info idx ->
"Object_variable_info: { " ^ U16.to_string idx ^ " }"
| Uninitialized_variable_info offset ->
"Uninitialized_variable_info: { " ^ U16.to_string offset ^ " }"
type t_full_frame =
{ offset_delta : U16.t
; locals : t_verification_type_info array
; stack : t_verification_type_info array
}
type t_stack_map_frame =
| Same_frame
| Same_locals_1_stack_item_frame of t_verification_type_info
| Same_locals_1_stack_item_frame_extended of U16.t * t_verification_type_info
| Chop_frame of U16.t
| Same_frame_extended of U16.t
| Append_frame of U16.t * t_verification_type_info array
| Full_frame of t_full_frame
type t =
| Code of t_code * t array
| Line_number_table of t_line_number array
| Source_file of U16.t
| Stack_map_table of t_stack_map_frame array
| Not_implemented
let read_attribute_name ic cp =
let attribute_name_index = U16.read ic |> U16.to_int in
let _attribute_length = U32.read ic in
Cp_info.unwrap_utf8 cp.(attribute_name_index - 1)
|> Result.map Cp_info.utf8_to_string
let read_verification_type_info ic =
try
Result.ok
@@
match U8.read ic |> U8.to_int with
| 0 -> Top_variable_info
| 1 -> Integer_variable_info
| 2 -> Float_variable_info
| 3 -> Long_variable_info
| 4 -> Double_variable_info
| 5 -> Null_variable_info
| 6 -> UninitializedThis_variable_info
| 7 -> Object_variable_info (U16.read ic)
| 8 -> Uninitialized_variable_info (U16.read ic)
| _ -> invalid_arg "read_verification_type_info: out of range"
with e -> Result.error e
let read_stack_map_frame ic =
let open Result_ext.Ops in
let frame_type = U8.read ic |> U8.to_int in
match frame_type with
| n when 0 <= n && n <= 63 -> Result.ok Same_frame
| n when n <= 127 ->
Result.map (fun v -> Same_locals_1_stack_item_frame v)
@@ read_verification_type_info ic
| n when n <= 246 ->
Result.error @@ invalid_arg "read_stack_map_frame : reserved for future use"
| 247 ->
let u16 = U16.read ic in
let+ verification_type_info = read_verification_type_info ic in
Same_locals_1_stack_item_frame_extended (u16, verification_type_info)
| n when n <= 250 -> Result.ok @@ Chop_frame (U16.read ic)
| 251 -> Result.ok @@ Same_frame_extended (U16.read ic)
| n when n <= 254 ->
let u16 = U16.read ic in
let+ arr =
let n = n - 251 and f _ = read_verification_type_info ic in
Result_ext.n_bind ~n ~f
in
Append_frame (u16, arr)
| 255 ->
let f _ = read_verification_type_info ic in
let offset_delta = U16.read ic in
let number_of_locals = U16.read ic |> U16.to_int in
let* locals = Result_ext.n_bind ~n:number_of_locals ~f in
let number_of_stack_items = U16.read ic |> U16.to_int in
let+ stack = Result_ext.n_bind ~n:number_of_stack_items ~f in
Full_frame { offset_delta; locals; stack }
| _ -> Result.error @@ invalid_arg "read_stack_map_frame : out of range"
let rec read ic cp =
let open Result_ext.Ops in
let* attribute_name = read_attribute_name ic cp in
match attribute_name with
| "Code" ->
let max_stack = U16.read ic |> U16.to_int
and max_locals = U16.read ic |> U16.to_int
and code_length = U32.read ic |> U32.to_int in
let code = Array.init code_length (fun _ -> U8.read ic |> U8.to_int) in
let exception_table_length = U16.read ic |> U16.to_int in
let f _ =
let start_pc = U16.read ic in
let end_pc = U16.read ic in
let handler_pc = U16.read ic in
let catch_type = U16.read ic in
{ start_pc; end_pc; handler_pc; catch_type }
in
let exception_table = Array.init exception_table_length f in
let attributes_count = U16.read ic |> U16.to_int in
let+ attributes =
let f _ = read ic cp in
Result_ext.n_bind ~n:attributes_count ~f
in
let code = { max_stack; max_locals; code; exception_table } in
Code (code, attributes)
| "LineNumberTable" ->
let line_number_table_length = U16.read ic |> U16.to_int in
let f _ =
let start_pc = U16.read ic in
let line_number = U16.read ic in
{ start_pc; line_number }
in
Result.ok @@ Line_number_table (Array.init line_number_table_length f)
| "SourceFile" -> Result.ok @@ Source_file (U16.read ic)
| "StackMapTable" ->
let n = U16.read ic |> U16.to_int in
let f _ = read_stack_map_frame ic in
let+ entries = Result_ext.n_bind ~n ~f in
Stack_map_table entries
| s ->
print_endline @@ "not implemented read_attribute " ^ s;
Result.ok Not_implemented
| null | https://raw.githubusercontent.com/lmdexpr/ocaml_jvm/549271581f6fd894059cb0769757099bee0bfa97/src/classfile/attribute_info.ml | ocaml | open Ubytes.Reader
type t_exception =
{ start_pc : U16.t
; end_pc : U16.t
; handler_pc : U16.t
; catch_type : U16.t
}
type t_line_number =
{ start_pc : U16.t
; line_number : U16.t
}
type t_code =
{ max_stack : int
; max_locals : int
; code : int array
; exception_table : t_exception array
}
type t_verification_type_info =
| Top_variable_info
| Integer_variable_info
| Float_variable_info
| Long_variable_info
| Double_variable_info
| Null_variable_info
| UninitializedThis_variable_info
| Object_variable_info of U16.t
| Uninitialized_variable_info of U16.t
let verification_type_info_to_string = function
| Top_variable_info -> "Top_variable_info"
| Integer_variable_info -> "Integer_variable_info"
| Float_variable_info -> "Float_variable_info"
| Long_variable_info -> "Long_variable_info"
| Double_variable_info -> "Double_variable_info"
| Null_variable_info -> "Null_variable_info"
| UninitializedThis_variable_info -> "UninitializedThis_variable_info"
| Object_variable_info idx ->
"Object_variable_info: { " ^ U16.to_string idx ^ " }"
| Uninitialized_variable_info offset ->
"Uninitialized_variable_info: { " ^ U16.to_string offset ^ " }"
type t_full_frame =
{ offset_delta : U16.t
; locals : t_verification_type_info array
; stack : t_verification_type_info array
}
type t_stack_map_frame =
| Same_frame
| Same_locals_1_stack_item_frame of t_verification_type_info
| Same_locals_1_stack_item_frame_extended of U16.t * t_verification_type_info
| Chop_frame of U16.t
| Same_frame_extended of U16.t
| Append_frame of U16.t * t_verification_type_info array
| Full_frame of t_full_frame
type t =
| Code of t_code * t array
| Line_number_table of t_line_number array
| Source_file of U16.t
| Stack_map_table of t_stack_map_frame array
| Not_implemented
let read_attribute_name ic cp =
let attribute_name_index = U16.read ic |> U16.to_int in
let _attribute_length = U32.read ic in
Cp_info.unwrap_utf8 cp.(attribute_name_index - 1)
|> Result.map Cp_info.utf8_to_string
let read_verification_type_info ic =
try
Result.ok
@@
match U8.read ic |> U8.to_int with
| 0 -> Top_variable_info
| 1 -> Integer_variable_info
| 2 -> Float_variable_info
| 3 -> Long_variable_info
| 4 -> Double_variable_info
| 5 -> Null_variable_info
| 6 -> UninitializedThis_variable_info
| 7 -> Object_variable_info (U16.read ic)
| 8 -> Uninitialized_variable_info (U16.read ic)
| _ -> invalid_arg "read_verification_type_info: out of range"
with e -> Result.error e
let read_stack_map_frame ic =
let open Result_ext.Ops in
let frame_type = U8.read ic |> U8.to_int in
match frame_type with
| n when 0 <= n && n <= 63 -> Result.ok Same_frame
| n when n <= 127 ->
Result.map (fun v -> Same_locals_1_stack_item_frame v)
@@ read_verification_type_info ic
| n when n <= 246 ->
Result.error @@ invalid_arg "read_stack_map_frame : reserved for future use"
| 247 ->
let u16 = U16.read ic in
let+ verification_type_info = read_verification_type_info ic in
Same_locals_1_stack_item_frame_extended (u16, verification_type_info)
| n when n <= 250 -> Result.ok @@ Chop_frame (U16.read ic)
| 251 -> Result.ok @@ Same_frame_extended (U16.read ic)
| n when n <= 254 ->
let u16 = U16.read ic in
let+ arr =
let n = n - 251 and f _ = read_verification_type_info ic in
Result_ext.n_bind ~n ~f
in
Append_frame (u16, arr)
| 255 ->
let f _ = read_verification_type_info ic in
let offset_delta = U16.read ic in
let number_of_locals = U16.read ic |> U16.to_int in
let* locals = Result_ext.n_bind ~n:number_of_locals ~f in
let number_of_stack_items = U16.read ic |> U16.to_int in
let+ stack = Result_ext.n_bind ~n:number_of_stack_items ~f in
Full_frame { offset_delta; locals; stack }
| _ -> Result.error @@ invalid_arg "read_stack_map_frame : out of range"
let rec read ic cp =
let open Result_ext.Ops in
let* attribute_name = read_attribute_name ic cp in
match attribute_name with
| "Code" ->
let max_stack = U16.read ic |> U16.to_int
and max_locals = U16.read ic |> U16.to_int
and code_length = U32.read ic |> U32.to_int in
let code = Array.init code_length (fun _ -> U8.read ic |> U8.to_int) in
let exception_table_length = U16.read ic |> U16.to_int in
let f _ =
let start_pc = U16.read ic in
let end_pc = U16.read ic in
let handler_pc = U16.read ic in
let catch_type = U16.read ic in
{ start_pc; end_pc; handler_pc; catch_type }
in
let exception_table = Array.init exception_table_length f in
let attributes_count = U16.read ic |> U16.to_int in
let+ attributes =
let f _ = read ic cp in
Result_ext.n_bind ~n:attributes_count ~f
in
let code = { max_stack; max_locals; code; exception_table } in
Code (code, attributes)
| "LineNumberTable" ->
let line_number_table_length = U16.read ic |> U16.to_int in
let f _ =
let start_pc = U16.read ic in
let line_number = U16.read ic in
{ start_pc; line_number }
in
Result.ok @@ Line_number_table (Array.init line_number_table_length f)
| "SourceFile" -> Result.ok @@ Source_file (U16.read ic)
| "StackMapTable" ->
let n = U16.read ic |> U16.to_int in
let f _ = read_stack_map_frame ic in
let+ entries = Result_ext.n_bind ~n ~f in
Stack_map_table entries
| s ->
print_endline @@ "not implemented read_attribute " ^ s;
Result.ok Not_implemented
| |
71be11176de0dd669f83349953b1a02d03e2fd51821cdae80eefbe082d484282 | freizl/dive-into-haskell | tutorial1.hs | Informatics 1 - Functional Programming
-- Tutorial 1
--
Due : the tutorial of week 3 ( 4/5 Oct. )
import Data.Char
import Data.List
import Test.QuickCheck
1 .
-- List-comprehension version
halveEvens :: [Int] -> [Int]
halveEvens xs = [ x `div` 2 | x <- xs, isEven x]
isEven :: Int -> Bool
isEven x = x `mod` 2 == 0
-- Recursive version
halveEvensRec :: [Int] -> [Int]
halveEvensRec [] = []
halveEvensRec (x:xs)
| isEven x = x `div` 2 : halveEvensRec xs
| otherwise = halveEvensRec xs
-- Mutual test
prop_halveEvens :: [Int] -> Bool
prop_halveEvens xs = halveEvens xs == halveEvensRec xs
2 . inRange
-- List-comprehension version
inRange :: Int -> Int -> [Int] -> [Int]
inRange lo hi xs = [ x | x <- xs, x > lo && x < hi ]
-- NOTES: `&&` is not necessary here.
-- [x | x <- xs, lo <= x, x <= hi]
-- Recursive version
inRangeRec :: Int -> Int -> [Int] -> [Int]
inRangeRec _ _ [] = []
inRangeRec lo hi (x:xs)
| x > lo && x < hi = x : inRangeRec lo hi xs
| otherwise = inRangeRec lo hi xs
-- Mutual test
prop_inRange :: Int -> Int -> [Int] -> Bool
prop_inRange lo hi xs = inRange lo hi xs == inRangeRec lo hi xs
3 . sumPositives : sum up all the positive numbers in a list
-- List-comprehension version
countPositives :: [Int] -> Int
countPositives xs = length [ x | x <- xs, x > 0]
-- Recursive version
countPositivesRec :: [Int] -> Int
countPositivesRec = f 0
where f a [] = a
f a (x:xs)
| x > 0 = f (a+1) xs
| otherwise = f a xs
-- NOTES: inner function is not necessary.
-- Mutual test
prop_countPositives :: [Int] -> Bool
prop_countPositives xs = countPositives xs == countPositivesRec xs
4 .
-- Helper function
discount :: Int -> Int
discount = round . (* 0.9) . fromIntegral
reasonable :: Int -> Bool
reasonable = (<= 19900)
-- List-comprehension version
pennypincher :: [Int] -> Int
pennypincher xs = sum [ y | y <- [ discount x | x <- xs], reasonable y ]
-- Recursive version
pennypincherRec :: [Int] -> Int
pennypincherRec [] = 0
pennypincherRec xs = f 0 xs
where f s [] = s
f s (x:xs) = let d = discount x in
if reasonable d then f (s+d) xs else f s xs
-- NOTES: inner function is not necessary.
-- Mutual test
prop_pennypincher :: [Int] -> Bool
prop_pennypincher xs = pennypincher xs == pennypincherRec xs
5 .
-- List-comprehension version
multDigits :: String -> Int
multDigits xs = product [ digitToInt x | x <- xs, isDigit x]
-- Recursive version
multDigitsRec :: String -> Int
multDigitsRec = f 1
where f p [] = p
f p (x:xs) = if isDigit x
then f (p*digitToInt x) xs
else f p xs
-- NOTES: inner function is not necessary.
-- Mutual test
prop_multDigits :: String -> Bool
prop_multDigits xs = multDigits xs == multDigitsRec xs
6 . capitalise
-- List-comprehension version
capitalise :: String -> String
capitalise [] = []
capitalise (x:xs) = toUpper x : [ toLower y | y <- xs ]
-- Recursive version
capitaliseRec :: String -> String
capitaliseRec [] = []
capitaliseRec (x:xs) = toUpper x : f xs
where f [] = []
f (y:ys) = toLower y : f ys
-- Mutual test
prop_capitalise :: String -> Bool
prop_capitalise xs = capitalise xs == capitaliseRec xs
7 . title
-- List-comprehension version
title :: [String] -> [String]
title [] = []
title (x:xs) = capitalise x : [ toCapOrLower y | y <- xs ]
toCapOrLower xs = let l = length xs in
if l > 3
then capitalise xs
else toLowers xs
toLowers = map toLower
-- Recursive version
titleRec :: [String] -> [String]
titleRec [] = []
titleRec (x:xs) = capitalise x : f xs
where f [] = []
f (y:ys) = toCapOrLower y : f ys
-- mutual test
prop_title :: [String] -> Bool
prop_title xs = title xs == titleRec xs
-- Optional Material
8 . crosswordFind
hasChar :: Char -> Int -> String -> Bool
hasChar c p str = str !! p == c
-- List-comprehension version
crosswordFind :: Char -> Int -> Int -> [String] -> [String]
crosswordFind c p l xs
| xs == [] = []
| p < 0 = []
| l < 0 = []
| p + 1 >= l = []
| otherwise = [ x | x <- xs, length x == l && hasChar c p x ]
-- Recursive version
crosswordFindRec :: Char -> Int -> Int -> [String] -> [String]
crosswordFindRec c p l xs
| xs == [] = []
| p < 0 = []
| l < 0 = []
| p + 1 >= l = []
| otherwise = let y = head xs
ys = tail xs
b = length y == l && hasChar c p y in
if b
then y : crosswordFindRec c p l ys
else crosswordFindRec c p l ys
-- Mutual test
prop_crosswordFind :: Char -> Int -> Int -> [String] -> Bool
prop_crosswordFind c p l xs = crosswordFind c p l xs == crosswordFindRec c p l xs
9 . search
-- List-comprehension version
search :: String -> Char -> [Int]
search xs c = [ y2 | (y1,y2) <- zip xs [0..], y1 == c ]
-- Recursive version
searchRec :: String -> Char -> [Int]
searchRec xs c = f 0 [] xs
where f i ys [] = ys
f i ys (z:zs) = if z == c
then f (i+1) (ys++[i]) zs
else f (i+1) ys zs
-- Mutual test
prop_search :: String -> Char -> Bool
prop_search xs c = search xs c == searchRec xs c
10 . contains
-- List-comprehension version
contains :: String -> String -> Bool
contains [] [] = True
contains xs ys
| length xs < length ys = False
| otherwise = let hi = length xs - length ys + 1
possibles = [ drop i xs | i <- [1..hi] ]
bools = [ b | b <- possibles, ys `isPrefixOf` b ] in
length bools > 0
-- Recursive version
containsRec :: String -> String -> Bool
containsRec [] [] = True
containsRec xs ys
| length xs < length ys = False
| otherwise = let b = ys `isPrefixOf` xs in
if b then True else containsRec (drop 1 xs) ys
-- NOTES: any elegant way to improve if.then.else part???
-- check solution
-- Mutual test
prop_contains :: String -> String -> Bool
prop_contains xs ys = contains xs ys == containsRec xs ys
| null | https://raw.githubusercontent.com/freizl/dive-into-haskell/b18a6bfe212db6c3a5d707b4a640170b8bcf9330/lectures/informatics1-FP/2011-haisheng/tutorial1/tutorial1.hs | haskell | Tutorial 1
List-comprehension version
Recursive version
Mutual test
List-comprehension version
NOTES: `&&` is not necessary here.
[x | x <- xs, lo <= x, x <= hi]
Recursive version
Mutual test
List-comprehension version
Recursive version
NOTES: inner function is not necessary.
Mutual test
Helper function
List-comprehension version
Recursive version
NOTES: inner function is not necessary.
Mutual test
List-comprehension version
Recursive version
NOTES: inner function is not necessary.
Mutual test
List-comprehension version
Recursive version
Mutual test
List-comprehension version
Recursive version
mutual test
Optional Material
List-comprehension version
Recursive version
Mutual test
List-comprehension version
Recursive version
Mutual test
List-comprehension version
Recursive version
NOTES: any elegant way to improve if.then.else part???
check solution
Mutual test | Informatics 1 - Functional Programming
Due : the tutorial of week 3 ( 4/5 Oct. )
import Data.Char
import Data.List
import Test.QuickCheck
1 .
halveEvens :: [Int] -> [Int]
halveEvens xs = [ x `div` 2 | x <- xs, isEven x]
isEven :: Int -> Bool
isEven x = x `mod` 2 == 0
halveEvensRec :: [Int] -> [Int]
halveEvensRec [] = []
halveEvensRec (x:xs)
| isEven x = x `div` 2 : halveEvensRec xs
| otherwise = halveEvensRec xs
prop_halveEvens :: [Int] -> Bool
prop_halveEvens xs = halveEvens xs == halveEvensRec xs
2 . inRange
inRange :: Int -> Int -> [Int] -> [Int]
inRange lo hi xs = [ x | x <- xs, x > lo && x < hi ]
inRangeRec :: Int -> Int -> [Int] -> [Int]
inRangeRec _ _ [] = []
inRangeRec lo hi (x:xs)
| x > lo && x < hi = x : inRangeRec lo hi xs
| otherwise = inRangeRec lo hi xs
prop_inRange :: Int -> Int -> [Int] -> Bool
prop_inRange lo hi xs = inRange lo hi xs == inRangeRec lo hi xs
3 . sumPositives : sum up all the positive numbers in a list
countPositives :: [Int] -> Int
countPositives xs = length [ x | x <- xs, x > 0]
countPositivesRec :: [Int] -> Int
countPositivesRec = f 0
where f a [] = a
f a (x:xs)
| x > 0 = f (a+1) xs
| otherwise = f a xs
prop_countPositives :: [Int] -> Bool
prop_countPositives xs = countPositives xs == countPositivesRec xs
4 .
discount :: Int -> Int
discount = round . (* 0.9) . fromIntegral
reasonable :: Int -> Bool
reasonable = (<= 19900)
pennypincher :: [Int] -> Int
pennypincher xs = sum [ y | y <- [ discount x | x <- xs], reasonable y ]
pennypincherRec :: [Int] -> Int
pennypincherRec [] = 0
pennypincherRec xs = f 0 xs
where f s [] = s
f s (x:xs) = let d = discount x in
if reasonable d then f (s+d) xs else f s xs
prop_pennypincher :: [Int] -> Bool
prop_pennypincher xs = pennypincher xs == pennypincherRec xs
5 .
multDigits :: String -> Int
multDigits xs = product [ digitToInt x | x <- xs, isDigit x]
multDigitsRec :: String -> Int
multDigitsRec = f 1
where f p [] = p
f p (x:xs) = if isDigit x
then f (p*digitToInt x) xs
else f p xs
prop_multDigits :: String -> Bool
prop_multDigits xs = multDigits xs == multDigitsRec xs
6 . capitalise
capitalise :: String -> String
capitalise [] = []
capitalise (x:xs) = toUpper x : [ toLower y | y <- xs ]
capitaliseRec :: String -> String
capitaliseRec [] = []
capitaliseRec (x:xs) = toUpper x : f xs
where f [] = []
f (y:ys) = toLower y : f ys
prop_capitalise :: String -> Bool
prop_capitalise xs = capitalise xs == capitaliseRec xs
7 . title
title :: [String] -> [String]
title [] = []
title (x:xs) = capitalise x : [ toCapOrLower y | y <- xs ]
toCapOrLower xs = let l = length xs in
if l > 3
then capitalise xs
else toLowers xs
toLowers = map toLower
titleRec :: [String] -> [String]
titleRec [] = []
titleRec (x:xs) = capitalise x : f xs
where f [] = []
f (y:ys) = toCapOrLower y : f ys
prop_title :: [String] -> Bool
prop_title xs = title xs == titleRec xs
8 . crosswordFind
hasChar :: Char -> Int -> String -> Bool
hasChar c p str = str !! p == c
crosswordFind :: Char -> Int -> Int -> [String] -> [String]
crosswordFind c p l xs
| xs == [] = []
| p < 0 = []
| l < 0 = []
| p + 1 >= l = []
| otherwise = [ x | x <- xs, length x == l && hasChar c p x ]
crosswordFindRec :: Char -> Int -> Int -> [String] -> [String]
crosswordFindRec c p l xs
| xs == [] = []
| p < 0 = []
| l < 0 = []
| p + 1 >= l = []
| otherwise = let y = head xs
ys = tail xs
b = length y == l && hasChar c p y in
if b
then y : crosswordFindRec c p l ys
else crosswordFindRec c p l ys
prop_crosswordFind :: Char -> Int -> Int -> [String] -> Bool
prop_crosswordFind c p l xs = crosswordFind c p l xs == crosswordFindRec c p l xs
9 . search
search :: String -> Char -> [Int]
search xs c = [ y2 | (y1,y2) <- zip xs [0..], y1 == c ]
searchRec :: String -> Char -> [Int]
searchRec xs c = f 0 [] xs
where f i ys [] = ys
f i ys (z:zs) = if z == c
then f (i+1) (ys++[i]) zs
else f (i+1) ys zs
prop_search :: String -> Char -> Bool
prop_search xs c = search xs c == searchRec xs c
10 . contains
contains :: String -> String -> Bool
contains [] [] = True
contains xs ys
| length xs < length ys = False
| otherwise = let hi = length xs - length ys + 1
possibles = [ drop i xs | i <- [1..hi] ]
bools = [ b | b <- possibles, ys `isPrefixOf` b ] in
length bools > 0
containsRec :: String -> String -> Bool
containsRec [] [] = True
containsRec xs ys
| length xs < length ys = False
| otherwise = let b = ys `isPrefixOf` xs in
if b then True else containsRec (drop 1 xs) ys
prop_contains :: String -> String -> Bool
prop_contains xs ys = contains xs ys == containsRec xs ys
|
43d4c10af89c4feec09729c21be46500fb28367a5764e2607aba1e666ea5af1f | sellout/haskerwaul | Under.hs | module Haskerwaul.Category.Under
( module Haskerwaul.Category.Under
-- * extended modules
, module Haskerwaul.Category.Over
) where
import Haskerwaul.Category.Over
import Haskerwaul.Category.Opposite
| In our representation of an under ( or coslice ) category _ _ x / c _ _ , the
-- objects are /represented by/ the objects of the underlying category, but
-- the terms are still all morphisms.
--
-- = references
--
-- - [nLab](+category)
-- - [Wikipedia](#Coslice_category)
type Under c = Over (Op c)
| null | https://raw.githubusercontent.com/sellout/haskerwaul/cf54bd7ce5bf4f3d1fd0d9d991dc733785b66a73/src/Haskerwaul/Category/Under.hs | haskell | * extended modules
objects are /represented by/ the objects of the underlying category, but
the terms are still all morphisms.
= references
- [nLab](+category)
- [Wikipedia](#Coslice_category) | module Haskerwaul.Category.Under
( module Haskerwaul.Category.Under
, module Haskerwaul.Category.Over
) where
import Haskerwaul.Category.Over
import Haskerwaul.Category.Opposite
| In our representation of an under ( or coslice ) category _ _ x / c _ _ , the
type Under c = Over (Op c)
|
541c605d552e4149278db6f39596127a4aa5aa1eaf75865d80184363b41d03f6 | dwayne/eopl3 | interpreter.rkt | #lang eopl
(require "./env.rkt")
(require "./parser.rkt")
(provide
;; Expressed Values
num-val bool-val list-val
;; Interpreter
run)
(define (run s)
(let ([init-env (extend-env
'i (num-val 1)
(extend-env
'v (num-val 5)
(extend-env
'x (num-val 10)
(empty-env))))])
(value-of-program (parse s) init-env (end-cont))))
Program x Env x Cont - > FinalAnswer
(define (value-of-program prog env cont)
(cases program prog
[a-program (exp) (value-of-exp exp env cont)]))
Expression x Env x Cont - > FinalAnswer
(define (value-of-exp exp env cont)
(cases expression exp
[const-exp (n)
(apply-cont cont (num-val n))]
[var-exp (var)
(apply-cont cont (apply-env env var construct-proc-val))]
[diff-exp (exp1 exp2)
(value-of-exp exp1 env (diff1-cont exp2 env cont))]
[zero?-exp (exp1)
(value-of-exp exp1 env (zero1-cont cont))]
[cons-exp (exp1 exp2)
(value-of-exp exp1 env (cons1-cont exp2 env cont))]
[car-exp (exp1)
(value-of-exp exp1 env (car-cont cont))]
[cdr-exp (exp1)
(value-of-exp exp1 env (cdr-cont cont))]
[null?-exp (exp1)
(value-of-exp exp1 env (null-cont cont))]
[emptylist-exp ()
(apply-cont cont (list-val '()))]
[list-exp (exps)
(value-of-list-exp exps env cont)]
[if-exp (exp1 exp2 exp3)
(value-of-exp exp1 env (if-test-cont exp2 exp3 env cont))]
[let-exp (vars exps body)
(value-of-let-exps exps env (let-exps-cont vars body env cont) '())]
[proc-exp (var body)
(apply-cont cont (proc-val (procedure var body env)))]
[letrec-exp (proc-name bound-var proc-body letrec-body)
(value-of-exp
letrec-body
(extend-env-rec proc-name bound-var proc-body env)
cont)]
[call-exp (rator rand)
(value-of-exp rator env (rator-cont rand env cont))]))
(define (construct-proc-val var body saved-env)
(proc-val (procedure var body saved-env)))
(define (value-of-list-exp exps env cont)
(if (null? exps)
(apply-cont cont (list-val '()))
(value-of-exp (car exps) env (list-head-cont (cdr exps) env cont))))
(define (value-of-let-exps exps env cont vals)
(if (null? exps)
(apply-cont cont (list-val (reverse vals)))
(value-of-exp (car exps) env (let-head-cont (cdr exps) vals env cont))))
;; Continuations
;;
;; It uses a procedural representation.
(define (end-cont)
(lambda (val)
(eopl:printf "End of computation.~%")
val))
(define (zero1-cont cont)
(lambda (val)
( apply - cont cont ( if ( zero ? ( expval->num val ) )
; (bool-val #t)
; (bool-val #f)))
; This can be simplified to:
(apply-cont cont (bool-val (zero? (expval->num val))))))
(define (cons1-cont exp2 env cont)
(lambda (val1)
(value-of-exp exp2 env (cons2-cont val1 cont))))
(define (cons2-cont val1 cont)
(lambda (val2)
(apply-cont cont (list-val (cons val1 (expval->list val2))))))
(define (car-cont cont)
(lambda (val1)
(apply-cont cont (car (expval->list val1)))))
(define (cdr-cont cont)
(lambda (val1)
(apply-cont cont (list-val (cdr (expval->list val1))))))
(define (null-cont cont)
(lambda (val1)
(apply-cont cont (bool-val (null? (expval->list val1))))))
(define (list-head-cont tail env cont)
(lambda (head-val)
(value-of-list-exp tail env (list-tail-cont head-val cont))))
(define (list-tail-cont head-val cont)
(lambda (tail-val)
(apply-cont cont (list-val (cons head-val (expval->list tail-val))))))
(define (let-exps-cont vars body env cont)
(lambda (vals)
(value-of-exp body (extend-env-parallel vars (expval->list vals) env) cont)))
(define (let-head-cont tail vals env cont)
(lambda (val)
(value-of-let-exps tail env cont (cons val vals))))
(define (if-test-cont exp2 exp3 env cont)
(lambda (val)
(if (expval->bool val)
(value-of-exp exp2 env cont)
(value-of-exp exp3 env cont))))
(define (diff1-cont exp2 env cont)
(lambda (val1)
(value-of-exp exp2 env (diff2-cont val1 cont))))
(define (diff2-cont val1 cont)
(lambda (val2)
(apply-cont
cont
(num-val
(- (expval->num val1)
(expval->num val2))))))
(define (rator-cont rand env cont)
(lambda (proc-val)
(value-of-exp rand env (rand-cont proc-val cont))))
(define (rand-cont proc-val cont)
(lambda (arg)
(apply-procedure (expval->proc proc-val) arg cont)))
;; Cont x ExpVal -> FinalAnswer
(define (apply-cont cont val)
(cont val))
;; Procedure ADT
(define-datatype proc proc?
[procedure
(var identifier?)
(body expression?)
(saved-env env?)])
(define (apply-procedure proc1 val cont)
(cases proc proc1
[procedure (var body saved-env)
(value-of-exp body (extend-env var val saved-env) cont)]))
;; Values
;;
;; ExpVal = Int + Bool + Proc + List[EvalVal]
DenVal = ExpVal
(define-datatype expval expval?
[num-val (n number?)]
[bool-val (b boolean?)]
[proc-val (p proc?)]
[list-val (l list?)])
(define (expval->num val)
(cases expval val
[num-val (n) n]
[else (eopl:error 'expval->num "Not a number: ~s" val)]))
(define (expval->bool val)
(cases expval val
[bool-val (b) b]
[else (eopl:error 'expval->bool "Not a boolean: ~s" val)]))
(define (expval->proc val)
(cases expval val
[proc-val (p) p]
[else (eopl:error 'expval->proc "Not a procedure: ~s" val)]))
(define (expval->list val)
(cases expval val
[list-val (l) l]
[else (eopl:error 'expval->list "Not a list: ~s" val)]))
| null | https://raw.githubusercontent.com/dwayne/eopl3/9d5fdb2a8dafac3bc48852d49cda8b83e7a825cf/solutions/05-ch5/interpreters/racket/CONTINUATION-PASSING-5.7/interpreter.rkt | racket | Expressed Values
Interpreter
Continuations
It uses a procedural representation.
(bool-val #t)
(bool-val #f)))
This can be simplified to:
Cont x ExpVal -> FinalAnswer
Procedure ADT
Values
ExpVal = Int + Bool + Proc + List[EvalVal] | #lang eopl
(require "./env.rkt")
(require "./parser.rkt")
(provide
num-val bool-val list-val
run)
(define (run s)
(let ([init-env (extend-env
'i (num-val 1)
(extend-env
'v (num-val 5)
(extend-env
'x (num-val 10)
(empty-env))))])
(value-of-program (parse s) init-env (end-cont))))
Program x Env x Cont - > FinalAnswer
(define (value-of-program prog env cont)
(cases program prog
[a-program (exp) (value-of-exp exp env cont)]))
Expression x Env x Cont - > FinalAnswer
(define (value-of-exp exp env cont)
(cases expression exp
[const-exp (n)
(apply-cont cont (num-val n))]
[var-exp (var)
(apply-cont cont (apply-env env var construct-proc-val))]
[diff-exp (exp1 exp2)
(value-of-exp exp1 env (diff1-cont exp2 env cont))]
[zero?-exp (exp1)
(value-of-exp exp1 env (zero1-cont cont))]
[cons-exp (exp1 exp2)
(value-of-exp exp1 env (cons1-cont exp2 env cont))]
[car-exp (exp1)
(value-of-exp exp1 env (car-cont cont))]
[cdr-exp (exp1)
(value-of-exp exp1 env (cdr-cont cont))]
[null?-exp (exp1)
(value-of-exp exp1 env (null-cont cont))]
[emptylist-exp ()
(apply-cont cont (list-val '()))]
[list-exp (exps)
(value-of-list-exp exps env cont)]
[if-exp (exp1 exp2 exp3)
(value-of-exp exp1 env (if-test-cont exp2 exp3 env cont))]
[let-exp (vars exps body)
(value-of-let-exps exps env (let-exps-cont vars body env cont) '())]
[proc-exp (var body)
(apply-cont cont (proc-val (procedure var body env)))]
[letrec-exp (proc-name bound-var proc-body letrec-body)
(value-of-exp
letrec-body
(extend-env-rec proc-name bound-var proc-body env)
cont)]
[call-exp (rator rand)
(value-of-exp rator env (rator-cont rand env cont))]))
(define (construct-proc-val var body saved-env)
(proc-val (procedure var body saved-env)))
(define (value-of-list-exp exps env cont)
(if (null? exps)
(apply-cont cont (list-val '()))
(value-of-exp (car exps) env (list-head-cont (cdr exps) env cont))))
(define (value-of-let-exps exps env cont vals)
(if (null? exps)
(apply-cont cont (list-val (reverse vals)))
(value-of-exp (car exps) env (let-head-cont (cdr exps) vals env cont))))
(define (end-cont)
(lambda (val)
(eopl:printf "End of computation.~%")
val))
(define (zero1-cont cont)
(lambda (val)
( apply - cont cont ( if ( zero ? ( expval->num val ) )
(apply-cont cont (bool-val (zero? (expval->num val))))))
(define (cons1-cont exp2 env cont)
(lambda (val1)
(value-of-exp exp2 env (cons2-cont val1 cont))))
(define (cons2-cont val1 cont)
(lambda (val2)
(apply-cont cont (list-val (cons val1 (expval->list val2))))))
(define (car-cont cont)
(lambda (val1)
(apply-cont cont (car (expval->list val1)))))
(define (cdr-cont cont)
(lambda (val1)
(apply-cont cont (list-val (cdr (expval->list val1))))))
(define (null-cont cont)
(lambda (val1)
(apply-cont cont (bool-val (null? (expval->list val1))))))
(define (list-head-cont tail env cont)
(lambda (head-val)
(value-of-list-exp tail env (list-tail-cont head-val cont))))
(define (list-tail-cont head-val cont)
(lambda (tail-val)
(apply-cont cont (list-val (cons head-val (expval->list tail-val))))))
(define (let-exps-cont vars body env cont)
(lambda (vals)
(value-of-exp body (extend-env-parallel vars (expval->list vals) env) cont)))
(define (let-head-cont tail vals env cont)
(lambda (val)
(value-of-let-exps tail env cont (cons val vals))))
(define (if-test-cont exp2 exp3 env cont)
(lambda (val)
(if (expval->bool val)
(value-of-exp exp2 env cont)
(value-of-exp exp3 env cont))))
(define (diff1-cont exp2 env cont)
(lambda (val1)
(value-of-exp exp2 env (diff2-cont val1 cont))))
(define (diff2-cont val1 cont)
(lambda (val2)
(apply-cont
cont
(num-val
(- (expval->num val1)
(expval->num val2))))))
(define (rator-cont rand env cont)
(lambda (proc-val)
(value-of-exp rand env (rand-cont proc-val cont))))
(define (rand-cont proc-val cont)
(lambda (arg)
(apply-procedure (expval->proc proc-val) arg cont)))
(define (apply-cont cont val)
(cont val))
(define-datatype proc proc?
[procedure
(var identifier?)
(body expression?)
(saved-env env?)])
(define (apply-procedure proc1 val cont)
(cases proc proc1
[procedure (var body saved-env)
(value-of-exp body (extend-env var val saved-env) cont)]))
DenVal = ExpVal
(define-datatype expval expval?
[num-val (n number?)]
[bool-val (b boolean?)]
[proc-val (p proc?)]
[list-val (l list?)])
(define (expval->num val)
(cases expval val
[num-val (n) n]
[else (eopl:error 'expval->num "Not a number: ~s" val)]))
(define (expval->bool val)
(cases expval val
[bool-val (b) b]
[else (eopl:error 'expval->bool "Not a boolean: ~s" val)]))
(define (expval->proc val)
(cases expval val
[proc-val (p) p]
[else (eopl:error 'expval->proc "Not a procedure: ~s" val)]))
(define (expval->list val)
(cases expval val
[list-val (l) l]
[else (eopl:error 'expval->list "Not a list: ~s" val)]))
|
4f476ab2cad0dbafa4aa3cc14b9384e5f9ad0196c44fb2ec4f62224e80b48510 | helium/packet-purchaser | pp_udp_worker.erl | -module(pp_udp_worker).
-behavior(gen_server).
-include("packet_purchaser.hrl").
-include("semtech_udp.hrl").
%% ------------------------------------------------------------------
%% API Function Exports
%% ------------------------------------------------------------------
-export([
start_link/1,
push_data/4,
push_data/5,
update_address/2
]).
%% ------------------------------------------------------------------
gen_server Function Exports
%% ------------------------------------------------------------------
-export([
init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3
]).
%% ------------------------------------------------------------------
%% Test Function Exports
%% ------------------------------------------------------------------
-ifdef(TEST).
-export([get_port/1, get_address_and_port/1]).
-endif.
-define(SERVER, ?MODULE).
-define(PUSH_DATA_TICK, push_data_tick).
-define(PUSH_DATA_TIMER, timer:seconds(2)).
-define(PULL_DATA_TICK, pull_data_tick).
-define(PULL_DATA_TIMEOUT_TICK, pull_data_timeout_tick).
-define(PULL_DATA_TIMER, timer:seconds(10)).
-define(SHUTDOWN_TICK, shutdown_tick).
-define(SHUTDOWN_TIMER, timer:minutes(5)).
-record(state, {
location :: no_location | {pos_integer(), float(), float()},
pubkeybin :: libp2p_crypto:pubkey_bin(),
net_id :: non_neg_integer(),
socket :: pp_udp_socket:socket(),
push_data = #{} :: #{binary() => {binary(), reference()}},
pull_data :: {reference(), binary()} | undefined,
pull_data_timer :: non_neg_integer(),
shutdown_timer :: {Timeout :: non_neg_integer(), Timer :: reference()}
}).
%% ------------------------------------------------------------------
%% API Function Definitions
%% ------------------------------------------------------------------
start_link(Args) ->
gen_server:start_link(?SERVER, Args, []).
-spec push_data(
Pid :: pid(),
SCPacket :: blockchain_state_channel_packet_v1:packet(),
PacketTime :: pos_integer(),
HandlerPid :: pid()
) -> ok | {error, any()}.
push_data(WorkerPid, SCPacket, PacketTime, HandlerPid) ->
gen_server:cast(WorkerPid, {push_data, SCPacket, PacketTime, HandlerPid}).
-spec push_data(
Pid :: pid(),
SCPacket :: blockchain_state_channel_packet_v1:packet(),
PacketTime :: pos_integer(),
HandlerPid :: pid(),
Protocol :: {udp, string(), integer()}
) -> ok | {error, any()}.
push_data(WorkerPid, SCPacket, PacketTime, HandlerPid, Protocol) ->
ok = update_address(WorkerPid, Protocol),
gen_server:cast(WorkerPid, {push_data, SCPacket, PacketTime, HandlerPid}).
-spec update_address(
WorkerPid :: pid(),
Protocol ::
{udp, Address :: pp_udp_socket:socket_address(), Port :: pp_udp_socket:socket_port()}
) -> ok.
update_address(WorkerPid, {udp, Address, Port}) ->
gen_server:cast(WorkerPid, {update_address, Address, Port}).
-ifdef(TEST).
%% Get the port to communicate with the gateway.
-spec get_port(WorkerPid :: pid()) -> inet:port_number().
get_port(WorkerPid) ->
#state{socket = {socket, Socket, _, _}} = sys:get_state(WorkerPid),
{ok, Port} = inet:port(Socket),
Port.
%% Get the address and port the gateway most recently communicated with.
-spec get_address_and_port(WorkerPid :: pid()) -> pp_udp_socket:socket_info().
get_address_and_port(WorkerPid) ->
#state{socket = Socket} = sys:get_state(WorkerPid),
pp_udp_socket:get_address(Socket).
-endif.
%% ------------------------------------------------------------------
gen_server Function Definitions
%% ------------------------------------------------------------------
init(Args) ->
process_flag(trap_exit, true),
lager:info("~p init with ~p", [?SERVER, Args]),
PubKeyBin = maps:get(pubkeybin, Args),
NetID = maps:get(net_id, Args),
Address = maps:get(address, Args),
lager:md([{gateway_id, blockchain_utils:addr2name(PubKeyBin)}, {address, Address}]),
Port = maps:get(port, Args),
{ok, Socket} = pp_udp_socket:open({Address, Port}, maps:get(tee, Args, undefined)),
DisablePullData = maps:get(disable_pull_data, Args, false),
PullDataTimer = maps:get(pull_data_timer, Args, ?PULL_DATA_TIMER),
case DisablePullData of
true ->
ok;
false ->
Pull data immediately so we can establish a connection for the first
%% pull_response.
self() ! ?PULL_DATA_TICK,
schedule_pull_data(PullDataTimer)
end,
ok = pp_config:insert_udp_worker(NetID, self()),
ShutdownTimeout = maps:get(shutdown_timer, Args, ?SHUTDOWN_TIMER),
ShutdownRef = schedule_shutdown(ShutdownTimeout),
Location = pp_utils:get_hotspot_location(PubKeyBin),
lager:info("got location ~p for hotspot", [Location]),
State = #state{
location = Location,
pubkeybin = PubKeyBin,
net_id = NetID,
socket = Socket,
pull_data_timer = PullDataTimer,
shutdown_timer = {ShutdownTimeout, ShutdownRef}
},
{ok, State}.
handle_call(_Msg, _From, State) ->
lager:warning("rcvd unknown call msg: ~p from: ~p", [_Msg, _From]),
{reply, ok, State}.
handle_cast(
{update_address, Address, Port},
#state{socket = Socket0} = State
) ->
lager:debug("Updating address and port [old: ~p] [new: ~p]", [
pp_udp_socket:get_address(Socket0),
{Address, Port}
]),
{ok, Socket1} = pp_udp_socket:update_address(Socket0, {Address, Port}),
{noreply, State#state{socket = Socket1}};
handle_cast(
{push_data, SCPacket, PacketTime, _HandlerPid},
#state{
pubkeybin = _PubKeyBin,
push_data = PushData,
location = Loc,
shutdown_timer = {ShutdownTimeout, ShutdownRef}
} =
State
) ->
_ = erlang:cancel_timer(ShutdownRef),
{Token, Data} = handle_data(SCPacket, PacketTime, Loc),
{_Reply, TimerRef} = send_push_data(Token, Data, State),
{noreply, State#state{
push_data = maps:put(Token, {Data, TimerRef}, PushData),
shutdown_timer = {ShutdownTimeout, schedule_shutdown(ShutdownTimeout)}
}};
handle_cast(_Msg, State) ->
lager:warning("rcvd unknown cast msg: ~p", [_Msg]),
{noreply, State}.
handle_info(get_hotspot_location, #state{pubkeybin = PubKeyBin} = State) ->
Location = pp_utils:get_hotspot_location(PubKeyBin),
lager:info("got location ~p for hotspot", [Location]),
{noreply, State#state{location = Location}};
handle_info(
{udp, Socket, _Address, Port, Data},
#state{
socket = {socket, Socket, _, _}
} = State
) ->
lager:debug("got udp packet ~p from ~p:~p", [Data, _Address, Port]),
try handle_udp(Data, State) of
{noreply, _} = NoReply -> NoReply
catch
_E:_R ->
lager:error("failed to handle UDP packet ~p: ~p/~p", [Data, _E, _R]),
{noreply, State}
end;
handle_info(
{?PUSH_DATA_TICK, Token},
#state{push_data = PushData, pubkeybin = PBK, net_id = NetID} = State
) ->
case maps:get(Token, PushData, undefined) of
undefined ->
{noreply, State};
{_Data, _} ->
lager:debug("got push data timeout ~p, ignoring lack of ack", [Token]),
ok = pp_metrics:push_ack_missed(PBK, NetID),
{noreply, State#state{push_data = maps:remove(Token, PushData)}}
end;
handle_info(
?PULL_DATA_TICK,
State
) ->
{ok, RefAndToken} = send_pull_data(State),
{noreply, State#state{pull_data = RefAndToken}};
handle_info(
?PULL_DATA_TIMEOUT_TICK,
#state{pull_data_timer = PullDataTimer, pubkeybin = PBK, net_id = NetID} = State
) ->
lager:debug("got a pull data timeout, ignoring missed pull_ack [retry: ~p]", [PullDataTimer]),
ok = pp_metrics:pull_ack_missed(PBK, NetID),
_ = schedule_pull_data(PullDataTimer),
{noreply, State};
handle_info(?SHUTDOWN_TICK, #state{shutdown_timer = {ShutdownTimeout, _}} = State) ->
lager:info("shutting down, haven't sent data in ~p", [ShutdownTimeout]),
{stop, normal, State};
handle_info(_Msg, State) ->
lager:warning("rcvd unknown info msg: ~p, ~p", [_Msg, State]),
{noreply, State}.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
terminate(_Reason, #state{socket = Socket}) ->
lager:info("going down ~p", [_Reason]),
ok = pp_config:delete_udp_worker(self()),
ok = pp_udp_socket:close(Socket),
ok.
%% ------------------------------------------------------------------
%% Internal Function Definitions
%% ------------------------------------------------------------------
-spec handle_data(
SCPacket :: blockchain_state_channel_packet_v1:packet(),
PacketTime :: pos_integer(),
Location :: {pos_integer(), float(), float()} | no_location
) -> {binary(), binary()}.
handle_data(SCPacket, PacketTime, Location) ->
Packet = blockchain_state_channel_packet_v1:packet(SCPacket),
PubKeyBin = blockchain_state_channel_packet_v1:hotspot(SCPacket),
Region = blockchain_state_channel_packet_v1:region(SCPacket),
Token = semtech_udp:token(),
MAC = pp_utils:pubkeybin_to_mac(PubKeyBin),
Tmst = blockchain_helium_packet_v1:timestamp(Packet),
Payload = blockchain_helium_packet_v1:payload(Packet),
LocationMap =
case Location of
no_location -> #{};
{Index, Lat, Long} -> #{inde => Index, lati => Lat, long => Long}
end,
Data = semtech_udp:push_data(
Token,
MAC,
#{
time => iso8601:format(
calendar:system_time_to_universal_time(PacketTime, millisecond)
),
tmst => Tmst band 16#FFFFFFFF,
freq => blockchain_helium_packet_v1:frequency(Packet),
rfch => 0,
modu => <<"LORA">>,
codr => <<"4/5">>,
stat => 1,
chan => 0,
datr => erlang:list_to_binary(blockchain_helium_packet_v1:datarate(Packet)),
rssi => erlang:trunc(blockchain_helium_packet_v1:signal_strength(Packet)),
lsnr => blockchain_helium_packet_v1:snr(Packet),
size => erlang:byte_size(Payload),
data => base64:encode(Payload)
},
maps:merge(
#{
regi => Region,
pubk => libp2p_crypto:bin_to_b58(PubKeyBin)
},
LocationMap
)
),
{Token, Data}.
-spec handle_udp(binary(), #state{}) -> {noreply, #state{}}.
handle_udp(Data, State) ->
Identifier = semtech_udp:identifier(Data),
lager:debug("got udp ~p / ~p", [semtech_udp:identifier_to_atom(Identifier), Data]),
case semtech_udp:identifier(Data) of
?PUSH_ACK ->
handle_push_ack(Data, State);
?PULL_ACK ->
handle_pull_ack(Data, State);
?PULL_RESP ->
handle_pull_resp(Data, State);
_Id ->
lager:warning("got unknown identifier ~p for ~p", [_Id, Data]),
{noreply, State}
end.
-spec handle_push_ack(binary(), #state{}) -> {noreply, #state{}}.
handle_push_ack(
Data,
#state{
push_data = PushData,
pubkeybin = PBK,
net_id = NetID
} = State
) ->
Token = semtech_udp:token(Data),
case maps:get(Token, PushData, undefined) of
undefined ->
lager:debug("got unkown push ack ~p", [Token]),
{noreply, State};
{_, TimerRef} ->
lager:debug("got push ack ~p", [Token]),
_ = erlang:cancel_timer(TimerRef),
ok = pp_metrics:push_ack(PBK, NetID),
{noreply, State#state{push_data = maps:remove(Token, PushData)}}
end.
-spec handle_pull_ack(binary(), #state{}) -> {noreply, #state{}}.
handle_pull_ack(
_Data,
#state{
pull_data = undefined
} = State
) ->
lager:warning("got unknown pull ack for ~p", [_Data]),
{noreply, State};
handle_pull_ack(
Data,
#state{
pull_data = {PullDataRef, PullDataToken},
pull_data_timer = PullDataTimer,
pubkeybin = PBK,
net_id = NetID
} = State
) ->
case semtech_udp:token(Data) of
PullDataToken ->
erlang:cancel_timer(PullDataRef),
lager:debug("got pull ack for ~p", [PullDataToken]),
_ = schedule_pull_data(PullDataTimer),
ok = pp_metrics:pull_ack(PBK, NetID),
{noreply, State#state{pull_data = undefined}};
_UnknownToken ->
lager:warning("got unknown pull ack for ~p", [_UnknownToken]),
{noreply, State}
end.
handle_pull_resp(Data, #state{pubkeybin = PubKeyBin} = State) ->
case pp_roaming_downlink:lookup_handler(PubKeyBin) of
{error, _} ->
lager:warning("could not send downlink, no handler pids");
{ok, HandlerPid} ->
ok = do_handle_pull_resp(Data, HandlerPid),
Token = semtech_udp:token(Data),
_ = send_tx_ack(Token, State)
end,
{noreply, State}.
-spec do_handle_pull_resp(binary(), pid()) -> ok.
do_handle_pull_resp(Data, SCPid) when is_pid(SCPid) ->
Map = maps:get(<<"txpk">>, semtech_udp:json_data(Data)),
JSONData0 = maps:get(<<"data">>, Map),
JSONData1 =
try
base64:decode(JSONData0)
catch
_:_ ->
lager:warning("failed to decode pull_resp data ~p", [JSONData0]),
JSONData0
end,
DownlinkPacket = blockchain_helium_packet_v1:new_downlink(
JSONData1,
maps:get(<<"powe">>, Map),
maps:get(<<"tmst">>, Map),
maps:get(<<"freq">>, Map),
erlang:binary_to_list(maps:get(<<"datr">>, Map))
),
catch blockchain_state_channel_common:send_response(
SCPid,
blockchain_state_channel_response_v1:new(true, DownlinkPacket)
),
ok.
-spec schedule_pull_data(non_neg_integer()) -> reference().
schedule_pull_data(PullDataTimer) ->
_ = erlang:send_after(PullDataTimer, self(), ?PULL_DATA_TICK).
-spec schedule_shutdown(non_neg_integer()) -> reference().
schedule_shutdown(ShutdownTimer) ->
_ = erlang:send_after(ShutdownTimer, self(), ?SHUTDOWN_TICK).
-spec send_pull_data(#state{}) -> {ok, {reference(), binary()}} | {error, any()}.
send_pull_data(
#state{
pubkeybin = PubKeyBin,
socket = Socket,
pull_data_timer = PullDataTimer
}
) ->
Token = semtech_udp:token(),
Data = semtech_udp:pull_data(Token, pp_utils:pubkeybin_to_mac(PubKeyBin)),
case pp_udp_socket:send(Socket, Data) of
ok ->
lager:debug("sent pull data keepalive ~p", [Token]),
TimerRef = erlang:send_after(PullDataTimer, self(), ?PULL_DATA_TIMEOUT_TICK),
{ok, {TimerRef, Token}};
Error ->
lager:warning("failed to send pull data keepalive ~p: ~p", [Token, Error]),
Error
end.
-spec send_push_data(binary(), binary(), #state{}) -> {ok | {error, any()}, reference()}.
send_push_data(
Token,
Data,
#state{socket = Socket}
) ->
Reply = pp_udp_socket:send(Socket, Data),
TimerRef = erlang:send_after(?PUSH_DATA_TIMER, self(), {?PUSH_DATA_TICK, Token}),
lager:debug("sent ~p/~p to ~p replied: ~p", [
Token,
Data,
pp_udp_socket:get_address(Socket),
Reply
]),
{Reply, TimerRef}.
-spec send_tx_ack(binary(), #state{}) -> ok | {error, any()}.
send_tx_ack(
Token,
#state{pubkeybin = PubKeyBin, socket = Socket}
) ->
Data = semtech_udp:tx_ack(Token, pp_utils:pubkeybin_to_mac(PubKeyBin)),
Reply = pp_udp_socket:send(Socket, Data),
lager:debug("sent ~p/~p to ~p replied: ~p", [
Token,
Data,
pp_udp_socket:get_address(Socket),
Reply
]),
Reply.
| null | https://raw.githubusercontent.com/helium/packet-purchaser/51fd632e19953beaba7a01bcbe3748a399fb3161/src/pp_udp_worker.erl | erlang | ------------------------------------------------------------------
API Function Exports
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
------------------------------------------------------------------
Test Function Exports
------------------------------------------------------------------
------------------------------------------------------------------
API Function Definitions
------------------------------------------------------------------
Get the port to communicate with the gateway.
Get the address and port the gateway most recently communicated with.
------------------------------------------------------------------
------------------------------------------------------------------
pull_response.
------------------------------------------------------------------
Internal Function Definitions
------------------------------------------------------------------ | -module(pp_udp_worker).
-behavior(gen_server).
-include("packet_purchaser.hrl").
-include("semtech_udp.hrl").
-export([
start_link/1,
push_data/4,
push_data/5,
update_address/2
]).
gen_server Function Exports
-export([
init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3
]).
-ifdef(TEST).
-export([get_port/1, get_address_and_port/1]).
-endif.
-define(SERVER, ?MODULE).
-define(PUSH_DATA_TICK, push_data_tick).
-define(PUSH_DATA_TIMER, timer:seconds(2)).
-define(PULL_DATA_TICK, pull_data_tick).
-define(PULL_DATA_TIMEOUT_TICK, pull_data_timeout_tick).
-define(PULL_DATA_TIMER, timer:seconds(10)).
-define(SHUTDOWN_TICK, shutdown_tick).
-define(SHUTDOWN_TIMER, timer:minutes(5)).
-record(state, {
location :: no_location | {pos_integer(), float(), float()},
pubkeybin :: libp2p_crypto:pubkey_bin(),
net_id :: non_neg_integer(),
socket :: pp_udp_socket:socket(),
push_data = #{} :: #{binary() => {binary(), reference()}},
pull_data :: {reference(), binary()} | undefined,
pull_data_timer :: non_neg_integer(),
shutdown_timer :: {Timeout :: non_neg_integer(), Timer :: reference()}
}).
start_link(Args) ->
gen_server:start_link(?SERVER, Args, []).
-spec push_data(
Pid :: pid(),
SCPacket :: blockchain_state_channel_packet_v1:packet(),
PacketTime :: pos_integer(),
HandlerPid :: pid()
) -> ok | {error, any()}.
push_data(WorkerPid, SCPacket, PacketTime, HandlerPid) ->
gen_server:cast(WorkerPid, {push_data, SCPacket, PacketTime, HandlerPid}).
-spec push_data(
Pid :: pid(),
SCPacket :: blockchain_state_channel_packet_v1:packet(),
PacketTime :: pos_integer(),
HandlerPid :: pid(),
Protocol :: {udp, string(), integer()}
) -> ok | {error, any()}.
push_data(WorkerPid, SCPacket, PacketTime, HandlerPid, Protocol) ->
ok = update_address(WorkerPid, Protocol),
gen_server:cast(WorkerPid, {push_data, SCPacket, PacketTime, HandlerPid}).
-spec update_address(
WorkerPid :: pid(),
Protocol ::
{udp, Address :: pp_udp_socket:socket_address(), Port :: pp_udp_socket:socket_port()}
) -> ok.
update_address(WorkerPid, {udp, Address, Port}) ->
gen_server:cast(WorkerPid, {update_address, Address, Port}).
-ifdef(TEST).
-spec get_port(WorkerPid :: pid()) -> inet:port_number().
get_port(WorkerPid) ->
#state{socket = {socket, Socket, _, _}} = sys:get_state(WorkerPid),
{ok, Port} = inet:port(Socket),
Port.
-spec get_address_and_port(WorkerPid :: pid()) -> pp_udp_socket:socket_info().
get_address_and_port(WorkerPid) ->
#state{socket = Socket} = sys:get_state(WorkerPid),
pp_udp_socket:get_address(Socket).
-endif.
gen_server Function Definitions
init(Args) ->
process_flag(trap_exit, true),
lager:info("~p init with ~p", [?SERVER, Args]),
PubKeyBin = maps:get(pubkeybin, Args),
NetID = maps:get(net_id, Args),
Address = maps:get(address, Args),
lager:md([{gateway_id, blockchain_utils:addr2name(PubKeyBin)}, {address, Address}]),
Port = maps:get(port, Args),
{ok, Socket} = pp_udp_socket:open({Address, Port}, maps:get(tee, Args, undefined)),
DisablePullData = maps:get(disable_pull_data, Args, false),
PullDataTimer = maps:get(pull_data_timer, Args, ?PULL_DATA_TIMER),
case DisablePullData of
true ->
ok;
false ->
Pull data immediately so we can establish a connection for the first
self() ! ?PULL_DATA_TICK,
schedule_pull_data(PullDataTimer)
end,
ok = pp_config:insert_udp_worker(NetID, self()),
ShutdownTimeout = maps:get(shutdown_timer, Args, ?SHUTDOWN_TIMER),
ShutdownRef = schedule_shutdown(ShutdownTimeout),
Location = pp_utils:get_hotspot_location(PubKeyBin),
lager:info("got location ~p for hotspot", [Location]),
State = #state{
location = Location,
pubkeybin = PubKeyBin,
net_id = NetID,
socket = Socket,
pull_data_timer = PullDataTimer,
shutdown_timer = {ShutdownTimeout, ShutdownRef}
},
{ok, State}.
handle_call(_Msg, _From, State) ->
lager:warning("rcvd unknown call msg: ~p from: ~p", [_Msg, _From]),
{reply, ok, State}.
handle_cast(
{update_address, Address, Port},
#state{socket = Socket0} = State
) ->
lager:debug("Updating address and port [old: ~p] [new: ~p]", [
pp_udp_socket:get_address(Socket0),
{Address, Port}
]),
{ok, Socket1} = pp_udp_socket:update_address(Socket0, {Address, Port}),
{noreply, State#state{socket = Socket1}};
handle_cast(
{push_data, SCPacket, PacketTime, _HandlerPid},
#state{
pubkeybin = _PubKeyBin,
push_data = PushData,
location = Loc,
shutdown_timer = {ShutdownTimeout, ShutdownRef}
} =
State
) ->
_ = erlang:cancel_timer(ShutdownRef),
{Token, Data} = handle_data(SCPacket, PacketTime, Loc),
{_Reply, TimerRef} = send_push_data(Token, Data, State),
{noreply, State#state{
push_data = maps:put(Token, {Data, TimerRef}, PushData),
shutdown_timer = {ShutdownTimeout, schedule_shutdown(ShutdownTimeout)}
}};
handle_cast(_Msg, State) ->
lager:warning("rcvd unknown cast msg: ~p", [_Msg]),
{noreply, State}.
handle_info(get_hotspot_location, #state{pubkeybin = PubKeyBin} = State) ->
Location = pp_utils:get_hotspot_location(PubKeyBin),
lager:info("got location ~p for hotspot", [Location]),
{noreply, State#state{location = Location}};
handle_info(
{udp, Socket, _Address, Port, Data},
#state{
socket = {socket, Socket, _, _}
} = State
) ->
lager:debug("got udp packet ~p from ~p:~p", [Data, _Address, Port]),
try handle_udp(Data, State) of
{noreply, _} = NoReply -> NoReply
catch
_E:_R ->
lager:error("failed to handle UDP packet ~p: ~p/~p", [Data, _E, _R]),
{noreply, State}
end;
handle_info(
{?PUSH_DATA_TICK, Token},
#state{push_data = PushData, pubkeybin = PBK, net_id = NetID} = State
) ->
case maps:get(Token, PushData, undefined) of
undefined ->
{noreply, State};
{_Data, _} ->
lager:debug("got push data timeout ~p, ignoring lack of ack", [Token]),
ok = pp_metrics:push_ack_missed(PBK, NetID),
{noreply, State#state{push_data = maps:remove(Token, PushData)}}
end;
handle_info(
?PULL_DATA_TICK,
State
) ->
{ok, RefAndToken} = send_pull_data(State),
{noreply, State#state{pull_data = RefAndToken}};
handle_info(
?PULL_DATA_TIMEOUT_TICK,
#state{pull_data_timer = PullDataTimer, pubkeybin = PBK, net_id = NetID} = State
) ->
lager:debug("got a pull data timeout, ignoring missed pull_ack [retry: ~p]", [PullDataTimer]),
ok = pp_metrics:pull_ack_missed(PBK, NetID),
_ = schedule_pull_data(PullDataTimer),
{noreply, State};
handle_info(?SHUTDOWN_TICK, #state{shutdown_timer = {ShutdownTimeout, _}} = State) ->
lager:info("shutting down, haven't sent data in ~p", [ShutdownTimeout]),
{stop, normal, State};
handle_info(_Msg, State) ->
lager:warning("rcvd unknown info msg: ~p, ~p", [_Msg, State]),
{noreply, State}.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
terminate(_Reason, #state{socket = Socket}) ->
lager:info("going down ~p", [_Reason]),
ok = pp_config:delete_udp_worker(self()),
ok = pp_udp_socket:close(Socket),
ok.
-spec handle_data(
SCPacket :: blockchain_state_channel_packet_v1:packet(),
PacketTime :: pos_integer(),
Location :: {pos_integer(), float(), float()} | no_location
) -> {binary(), binary()}.
handle_data(SCPacket, PacketTime, Location) ->
Packet = blockchain_state_channel_packet_v1:packet(SCPacket),
PubKeyBin = blockchain_state_channel_packet_v1:hotspot(SCPacket),
Region = blockchain_state_channel_packet_v1:region(SCPacket),
Token = semtech_udp:token(),
MAC = pp_utils:pubkeybin_to_mac(PubKeyBin),
Tmst = blockchain_helium_packet_v1:timestamp(Packet),
Payload = blockchain_helium_packet_v1:payload(Packet),
LocationMap =
case Location of
no_location -> #{};
{Index, Lat, Long} -> #{inde => Index, lati => Lat, long => Long}
end,
Data = semtech_udp:push_data(
Token,
MAC,
#{
time => iso8601:format(
calendar:system_time_to_universal_time(PacketTime, millisecond)
),
tmst => Tmst band 16#FFFFFFFF,
freq => blockchain_helium_packet_v1:frequency(Packet),
rfch => 0,
modu => <<"LORA">>,
codr => <<"4/5">>,
stat => 1,
chan => 0,
datr => erlang:list_to_binary(blockchain_helium_packet_v1:datarate(Packet)),
rssi => erlang:trunc(blockchain_helium_packet_v1:signal_strength(Packet)),
lsnr => blockchain_helium_packet_v1:snr(Packet),
size => erlang:byte_size(Payload),
data => base64:encode(Payload)
},
maps:merge(
#{
regi => Region,
pubk => libp2p_crypto:bin_to_b58(PubKeyBin)
},
LocationMap
)
),
{Token, Data}.
-spec handle_udp(binary(), #state{}) -> {noreply, #state{}}.
handle_udp(Data, State) ->
Identifier = semtech_udp:identifier(Data),
lager:debug("got udp ~p / ~p", [semtech_udp:identifier_to_atom(Identifier), Data]),
case semtech_udp:identifier(Data) of
?PUSH_ACK ->
handle_push_ack(Data, State);
?PULL_ACK ->
handle_pull_ack(Data, State);
?PULL_RESP ->
handle_pull_resp(Data, State);
_Id ->
lager:warning("got unknown identifier ~p for ~p", [_Id, Data]),
{noreply, State}
end.
-spec handle_push_ack(binary(), #state{}) -> {noreply, #state{}}.
handle_push_ack(
Data,
#state{
push_data = PushData,
pubkeybin = PBK,
net_id = NetID
} = State
) ->
Token = semtech_udp:token(Data),
case maps:get(Token, PushData, undefined) of
undefined ->
lager:debug("got unkown push ack ~p", [Token]),
{noreply, State};
{_, TimerRef} ->
lager:debug("got push ack ~p", [Token]),
_ = erlang:cancel_timer(TimerRef),
ok = pp_metrics:push_ack(PBK, NetID),
{noreply, State#state{push_data = maps:remove(Token, PushData)}}
end.
-spec handle_pull_ack(binary(), #state{}) -> {noreply, #state{}}.
handle_pull_ack(
_Data,
#state{
pull_data = undefined
} = State
) ->
lager:warning("got unknown pull ack for ~p", [_Data]),
{noreply, State};
handle_pull_ack(
Data,
#state{
pull_data = {PullDataRef, PullDataToken},
pull_data_timer = PullDataTimer,
pubkeybin = PBK,
net_id = NetID
} = State
) ->
case semtech_udp:token(Data) of
PullDataToken ->
erlang:cancel_timer(PullDataRef),
lager:debug("got pull ack for ~p", [PullDataToken]),
_ = schedule_pull_data(PullDataTimer),
ok = pp_metrics:pull_ack(PBK, NetID),
{noreply, State#state{pull_data = undefined}};
_UnknownToken ->
lager:warning("got unknown pull ack for ~p", [_UnknownToken]),
{noreply, State}
end.
handle_pull_resp(Data, #state{pubkeybin = PubKeyBin} = State) ->
case pp_roaming_downlink:lookup_handler(PubKeyBin) of
{error, _} ->
lager:warning("could not send downlink, no handler pids");
{ok, HandlerPid} ->
ok = do_handle_pull_resp(Data, HandlerPid),
Token = semtech_udp:token(Data),
_ = send_tx_ack(Token, State)
end,
{noreply, State}.
-spec do_handle_pull_resp(binary(), pid()) -> ok.
do_handle_pull_resp(Data, SCPid) when is_pid(SCPid) ->
Map = maps:get(<<"txpk">>, semtech_udp:json_data(Data)),
JSONData0 = maps:get(<<"data">>, Map),
JSONData1 =
try
base64:decode(JSONData0)
catch
_:_ ->
lager:warning("failed to decode pull_resp data ~p", [JSONData0]),
JSONData0
end,
DownlinkPacket = blockchain_helium_packet_v1:new_downlink(
JSONData1,
maps:get(<<"powe">>, Map),
maps:get(<<"tmst">>, Map),
maps:get(<<"freq">>, Map),
erlang:binary_to_list(maps:get(<<"datr">>, Map))
),
catch blockchain_state_channel_common:send_response(
SCPid,
blockchain_state_channel_response_v1:new(true, DownlinkPacket)
),
ok.
-spec schedule_pull_data(non_neg_integer()) -> reference().
schedule_pull_data(PullDataTimer) ->
_ = erlang:send_after(PullDataTimer, self(), ?PULL_DATA_TICK).
-spec schedule_shutdown(non_neg_integer()) -> reference().
schedule_shutdown(ShutdownTimer) ->
_ = erlang:send_after(ShutdownTimer, self(), ?SHUTDOWN_TICK).
-spec send_pull_data(#state{}) -> {ok, {reference(), binary()}} | {error, any()}.
send_pull_data(
#state{
pubkeybin = PubKeyBin,
socket = Socket,
pull_data_timer = PullDataTimer
}
) ->
Token = semtech_udp:token(),
Data = semtech_udp:pull_data(Token, pp_utils:pubkeybin_to_mac(PubKeyBin)),
case pp_udp_socket:send(Socket, Data) of
ok ->
lager:debug("sent pull data keepalive ~p", [Token]),
TimerRef = erlang:send_after(PullDataTimer, self(), ?PULL_DATA_TIMEOUT_TICK),
{ok, {TimerRef, Token}};
Error ->
lager:warning("failed to send pull data keepalive ~p: ~p", [Token, Error]),
Error
end.
-spec send_push_data(binary(), binary(), #state{}) -> {ok | {error, any()}, reference()}.
send_push_data(
Token,
Data,
#state{socket = Socket}
) ->
Reply = pp_udp_socket:send(Socket, Data),
TimerRef = erlang:send_after(?PUSH_DATA_TIMER, self(), {?PUSH_DATA_TICK, Token}),
lager:debug("sent ~p/~p to ~p replied: ~p", [
Token,
Data,
pp_udp_socket:get_address(Socket),
Reply
]),
{Reply, TimerRef}.
-spec send_tx_ack(binary(), #state{}) -> ok | {error, any()}.
send_tx_ack(
Token,
#state{pubkeybin = PubKeyBin, socket = Socket}
) ->
Data = semtech_udp:tx_ack(Token, pp_utils:pubkeybin_to_mac(PubKeyBin)),
Reply = pp_udp_socket:send(Socket, Data),
lager:debug("sent ~p/~p to ~p replied: ~p", [
Token,
Data,
pp_udp_socket:get_address(Socket),
Reply
]),
Reply.
|
0c51415ddf52fbfde0861c7bb77de96281e1fb23feee3faefc06ebef403e77f7 | xxyzz/SICP | Exercise_2_12.rkt | #lang racket/base
(define (make-interval a b) (cons a b))
(define (upper-bound interval)
(max (car interval) (cdr interval)))
(define (lower-bound interval)
(min (car interval) (cdr interval)))
(define (make-center-percent c p)
(let ([tolerance (* c (/ p 100))])
(make-interval (- c tolerance) (+ c tolerance))))
(define (center i)
(/ (+ (lower-bound i) (upper-bound i)) 2))
(define (width i)
(/ (- (upper-bound i) (lower-bound i)) 2))
(define (percent i)
(* (/ (width i) (center i)) 100))
(make-center-percent 2 50)
' ( 1 . 3 )
(percent (make-center-percent 2 50))
50
| null | https://raw.githubusercontent.com/xxyzz/SICP/e26aea1c58fd896297dbf5406f7fcd32bb4f8f78/2_Building_Abstractions_with_Data/2.1_Introduction_to_Data_Abstraction/Exercise_2_12.rkt | racket | #lang racket/base
(define (make-interval a b) (cons a b))
(define (upper-bound interval)
(max (car interval) (cdr interval)))
(define (lower-bound interval)
(min (car interval) (cdr interval)))
(define (make-center-percent c p)
(let ([tolerance (* c (/ p 100))])
(make-interval (- c tolerance) (+ c tolerance))))
(define (center i)
(/ (+ (lower-bound i) (upper-bound i)) 2))
(define (width i)
(/ (- (upper-bound i) (lower-bound i)) 2))
(define (percent i)
(* (/ (width i) (center i)) 100))
(make-center-percent 2 50)
' ( 1 . 3 )
(percent (make-center-percent 2 50))
50
| |
4311d37059a32dc5417aa9c336a3fd2fb571dcd595a9b9c877853ee14c9ee4f2 | MaskRay/99-problems-ocaml | 66.ml | type 'a tree = Leaf | Branch of 'a * 'a tree * 'a tree
let rec pad x y = match x, y with
| [], y | y, [] -> y
| x::xs, y::ys -> x :: pad xs ys
let rec maximum = function
| [x] -> x
| h::t -> max h (maximum t)
let rec max_sum = function
| [], _ | _, [] -> 0
| a::b, c::d -> max (a+c) (max_sum (b, d))
let layout t =
let rec go = function
| Leaf -> ([], Leaf, [])
| Branch (a, l, r) ->
let ll, l', lr = go l in
let rl, r', rr = go r in
let sep = max_sum (lr, rl) / 2 + 1 in
( 0 :: pad (List.map ((+) sep) ll) (List.map (fun p -> p-sep) rl)
, Branch ((a, sep), l', r')
, 0 :: pad (List.map ((+) sep) rr) (List.map (fun p -> p-sep) lr)
) in
let rec go2 x y = function
| Leaf -> Leaf
| Branch ((a, dx), l, r) ->
Branch ( (a, x, y)
, go2 (x-dx) (y+1) l
, go2 (x+dx) (y+1) r) in
let l, t', r = go t in
go2 (maximum l + 1) 1 t'
| null | https://raw.githubusercontent.com/MaskRay/99-problems-ocaml/652604f13ba7a73eee06d359b4db549b49ec9bb3/61-70/66.ml | ocaml | type 'a tree = Leaf | Branch of 'a * 'a tree * 'a tree
let rec pad x y = match x, y with
| [], y | y, [] -> y
| x::xs, y::ys -> x :: pad xs ys
let rec maximum = function
| [x] -> x
| h::t -> max h (maximum t)
let rec max_sum = function
| [], _ | _, [] -> 0
| a::b, c::d -> max (a+c) (max_sum (b, d))
let layout t =
let rec go = function
| Leaf -> ([], Leaf, [])
| Branch (a, l, r) ->
let ll, l', lr = go l in
let rl, r', rr = go r in
let sep = max_sum (lr, rl) / 2 + 1 in
( 0 :: pad (List.map ((+) sep) ll) (List.map (fun p -> p-sep) rl)
, Branch ((a, sep), l', r')
, 0 :: pad (List.map ((+) sep) rr) (List.map (fun p -> p-sep) lr)
) in
let rec go2 x y = function
| Leaf -> Leaf
| Branch ((a, dx), l, r) ->
Branch ( (a, x, y)
, go2 (x-dx) (y+1) l
, go2 (x+dx) (y+1) r) in
let l, t', r = go t in
go2 (maximum l + 1) 1 t'
| |
72e4694052463813f096ce815e4313cb3436142b304ed661a380288a663447af | uw-unsat/leanette-popl22-artifact | synthesis.rkt | #lang rosette
(require racket/require
(multi-in "../../frameworks/alglave" ("models.rkt" "framework.rkt"))
"../../litmus/litmus.rkt"
(only-in "../../ocelot/ocelot.rkt" ast->datum simplify)
(only-in "../../memsynth/synth.rkt" synth-tests-used))
(provide run-synthesis-experiment)
;; Takes as input the name of a reference memory model (used for litmus-test-allowed?),
;; a list of litmus tests, and a memory model sketch.
Returns a synthesized model or # f.
(define (run-synthesis-experiment spec tests sketch)
(printf "Tests: ~v\n" (length tests))
(printf " positive: ~v\n" (length (filter (lambda (T) (litmus-test-allowed? spec T)) tests)))
(printf " negative: ~v\n" (length (filter (lambda (T) (not (litmus-test-allowed? spec T))) tests)))
(printf "\nSketch state space: 2^~v\n" (length (symbolics sketch)))
;; synth takes as input a list of (test, outcome) pairs
(define test-outcomes (for/list ([T tests]) (cons T (litmus-test-allowed? spec T))))
;; Run the synthesis engine
(printf "\nSynthesizing...\n")
(define t0 (current-inexact-milliseconds))
(define model (synth alglave test-outcomes sketch))
(define t (- (current-inexact-milliseconds) t0))
(printf "\nSynthesis complete!\n")
(printf "time: ~a ms\n" (~r t #:precision 0))
(printf "tests used: ~v/~v\n\n" synth-tests-used (length tests))
(cond
[model
(printf "solution: ppo: ~a\n" (ast->datum (simplify (model-ppo model))))
(printf " grf: ~a\n" (ast->datum (simplify (model-grf model))))
(printf " ab: ~a\n" (ast->datum (simplify (model-ab model))))]
[else
(printf "no solution found\n")])
;; Verify the solution
(when model
(printf "\nVerifying solution...\n")
(define successes
(for/sum ([T tests])
(define ret (allowed? alglave T model))
(if (eq? ret (litmus-test-allowed? spec T))
1
(begin
(printf "ERROR: wrong outcome for test ~v\n" (litmus-test-name T))
0))))
(printf "Verified ~v litmus tests\n" successes))
model)
| null | https://raw.githubusercontent.com/uw-unsat/leanette-popl22-artifact/80fea2519e61b45a283fbf7903acdf6d5528dbe7/rosette-benchmarks-3/memsynth/case-studies/synthesis/synthesis.rkt | racket | Takes as input the name of a reference memory model (used for litmus-test-allowed?),
a list of litmus tests, and a memory model sketch.
synth takes as input a list of (test, outcome) pairs
Run the synthesis engine
Verify the solution | #lang rosette
(require racket/require
(multi-in "../../frameworks/alglave" ("models.rkt" "framework.rkt"))
"../../litmus/litmus.rkt"
(only-in "../../ocelot/ocelot.rkt" ast->datum simplify)
(only-in "../../memsynth/synth.rkt" synth-tests-used))
(provide run-synthesis-experiment)
Returns a synthesized model or # f.
(define (run-synthesis-experiment spec tests sketch)
(printf "Tests: ~v\n" (length tests))
(printf " positive: ~v\n" (length (filter (lambda (T) (litmus-test-allowed? spec T)) tests)))
(printf " negative: ~v\n" (length (filter (lambda (T) (not (litmus-test-allowed? spec T))) tests)))
(printf "\nSketch state space: 2^~v\n" (length (symbolics sketch)))
(define test-outcomes (for/list ([T tests]) (cons T (litmus-test-allowed? spec T))))
(printf "\nSynthesizing...\n")
(define t0 (current-inexact-milliseconds))
(define model (synth alglave test-outcomes sketch))
(define t (- (current-inexact-milliseconds) t0))
(printf "\nSynthesis complete!\n")
(printf "time: ~a ms\n" (~r t #:precision 0))
(printf "tests used: ~v/~v\n\n" synth-tests-used (length tests))
(cond
[model
(printf "solution: ppo: ~a\n" (ast->datum (simplify (model-ppo model))))
(printf " grf: ~a\n" (ast->datum (simplify (model-grf model))))
(printf " ab: ~a\n" (ast->datum (simplify (model-ab model))))]
[else
(printf "no solution found\n")])
(when model
(printf "\nVerifying solution...\n")
(define successes
(for/sum ([T tests])
(define ret (allowed? alglave T model))
(if (eq? ret (litmus-test-allowed? spec T))
1
(begin
(printf "ERROR: wrong outcome for test ~v\n" (litmus-test-name T))
0))))
(printf "Verified ~v litmus tests\n" successes))
model)
|
6809ae29e8fe8ce211115fed80d06cad239b28ecd73b357fcc179ccb35500499 | oisdk/monus-weighted-search | SubsetSum.hs | -- |
Module : MonusWeightedSearch . Examples . SubsetSum
Copyright : ( c ) Kidney 2021
-- Maintainer :
-- Stability : experimental
-- Portability : non-portable
--
An implementation of shortest subset sum ( the Inclusion - Exclusion method )
-- using the 'Heap' monad.
module MonusWeightedSearch.Examples.SubsetSum where
import Control.Monad.Heap
import Data.Monus.Dist
import Control.Monad.Writer
import Data.Maybe
import Control.Monad (filterM, guard)
-- | A weight for the inclusion or exclusion of an element.
--
-- This lets us weight the computation by number of elements included, and
-- therefore optimise for the fewest.
inclusion :: Monad m => HeapT Dist m Bool
inclusion = fromList [(False,0),(True,1)]
| @'shortest ' n xs@ returns the shortes subset of @xs@ which sums to @n@.
--
> > > shortest 5 [ 10,-4,3,11,6,12,1 ]
-- [-4,3,6]
shortest :: Int -> [Int] -> [Int]
shortest t xs = snd . fromJust . best $ do
subset <- filterM (const inclusion) xs
guard (sum subset == t)
pure subset
| null | https://raw.githubusercontent.com/oisdk/monus-weighted-search/f2f3fdeb6ddcc555477df6d23d3ef0031017ca86/src/MonusWeightedSearch/Examples/SubsetSum.hs | haskell | |
Maintainer :
Stability : experimental
Portability : non-portable
using the 'Heap' monad.
| A weight for the inclusion or exclusion of an element.
This lets us weight the computation by number of elements included, and
therefore optimise for the fewest.
[-4,3,6] | Module : MonusWeightedSearch . Examples . SubsetSum
Copyright : ( c ) Kidney 2021
An implementation of shortest subset sum ( the Inclusion - Exclusion method )
module MonusWeightedSearch.Examples.SubsetSum where
import Control.Monad.Heap
import Data.Monus.Dist
import Control.Monad.Writer
import Data.Maybe
import Control.Monad (filterM, guard)
inclusion :: Monad m => HeapT Dist m Bool
inclusion = fromList [(False,0),(True,1)]
| @'shortest ' n xs@ returns the shortes subset of @xs@ which sums to @n@.
> > > shortest 5 [ 10,-4,3,11,6,12,1 ]
shortest :: Int -> [Int] -> [Int]
shortest t xs = snd . fromJust . best $ do
subset <- filterM (const inclusion) xs
guard (sum subset == t)
pure subset
|
438e823151036683045bb02a3e9127603c02709d56343626d03383dc6b60e116 | chaoxu/fancy-walks | 119.hs | {-# OPTIONS_GHC -O2 #-}
import Data.List
import Data . Int
minusOrd :: Ord a => [a] -> [a] -> [a]
minusOrd a@(x:xs) b@(y:ys) = case compare x y of
EQ -> minusOrd xs ys
LT -> x : minusOrd xs b
GT -> minusOrd a ys
minusOrd xs _ = xs
unionOrd :: Ord a => [a] -> [a] -> [a]
unionOrd a@(x:xs) b@(y:ys) = case compare x y of
EQ -> x : unionOrd xs ys
LT -> x : unionOrd xs b
GT -> y : unionOrd a ys
unionOrd xs ys = xs ++ ys
pairsOrd :: Ord a => [[a]] -> [[a]]
pairsOrd [] = []
pairsOrd [xs] = [xs]
pairsOrd ((x:xs):ys:remain) = (x : unionOrd xs ys) : pairsOrd remain
joinOrd :: Ord a => [[a]] -> [a]
joinOrd [] = []
joinOrd [xs] = xs
joinOrd ((x:xs):remain) = x : unionOrd xs (joinOrd (pairsOrd remain))
primes = sieve [2..]
where
sieve (x:xs) = x : sieve (filter ((/=0).(`mod` x)) xs)
powerNumber = dropWhile (<10) $ joinOrd [map (^i) [2..] | i <- primes]
digitSum 0 = 0
digitSum x = let (a, b) = x `divMod` 10 in digitSum a + b
check n
| d == 1 = False
| otherwise = n `mod` d == 0 && go (d^2)
where
d = digitSum n
go x | x > n = False
| x == n = True
| otherwise = go (x * d)
interestings = filter check powerNumber
problem_119 = interestings !! 29
main = print problem_119
| null | https://raw.githubusercontent.com/chaoxu/fancy-walks/952fcc345883181144131f839aa61e36f488998d/projecteuler.net/119.hs | haskell | # OPTIONS_GHC -O2 # |
import Data.List
import Data . Int
minusOrd :: Ord a => [a] -> [a] -> [a]
minusOrd a@(x:xs) b@(y:ys) = case compare x y of
EQ -> minusOrd xs ys
LT -> x : minusOrd xs b
GT -> minusOrd a ys
minusOrd xs _ = xs
unionOrd :: Ord a => [a] -> [a] -> [a]
unionOrd a@(x:xs) b@(y:ys) = case compare x y of
EQ -> x : unionOrd xs ys
LT -> x : unionOrd xs b
GT -> y : unionOrd a ys
unionOrd xs ys = xs ++ ys
pairsOrd :: Ord a => [[a]] -> [[a]]
pairsOrd [] = []
pairsOrd [xs] = [xs]
pairsOrd ((x:xs):ys:remain) = (x : unionOrd xs ys) : pairsOrd remain
joinOrd :: Ord a => [[a]] -> [a]
joinOrd [] = []
joinOrd [xs] = xs
joinOrd ((x:xs):remain) = x : unionOrd xs (joinOrd (pairsOrd remain))
primes = sieve [2..]
where
sieve (x:xs) = x : sieve (filter ((/=0).(`mod` x)) xs)
powerNumber = dropWhile (<10) $ joinOrd [map (^i) [2..] | i <- primes]
digitSum 0 = 0
digitSum x = let (a, b) = x `divMod` 10 in digitSum a + b
check n
| d == 1 = False
| otherwise = n `mod` d == 0 && go (d^2)
where
d = digitSum n
go x | x > n = False
| x == n = True
| otherwise = go (x * d)
interestings = filter check powerNumber
problem_119 = interestings !! 29
main = print problem_119
|
c86767a35bd56d8a3a37c186b928fad8b8c8423840bd2248f39fbfedcf912a4b | ds-wizard/engine-backend | ServerConfigJM.hs | module Registry.Model.Config.ServerConfigJM where
import Control.Monad
import Data.Aeson
import Registry.Model.Config.ServerConfig
import Registry.Model.Config.ServerConfigDM
import Shared.Model.Config.EnvironmentJM ()
import Shared.Model.Config.ServerConfigDM
import Shared.Model.Config.ServerConfigJM ()
instance FromJSON ServerConfig where
parseJSON (Object o) = do
general <- o .: "general"
database <- o .:? "database" .!= defaultDatabase
s3 <- o .:? "s3" .!= defaultS3
analytics <- o .:? "analytics" .!= defaultAnalytics
sentry <- o .:? "sentry" .!= defaultSentry
logging <- o .:? "logging" .!= defaultLogging
cloud <- o .:? "cloud" .!= defaultCloud
return ServerConfig {..}
parseJSON _ = mzero
instance FromJSON ServerConfigGeneral where
parseJSON (Object o) = do
environment <- o .:? "environment" .!= defaultGeneral.environment
clientUrl <- o .: "clientUrl"
serverPort <- o .:? "serverPort" .!= defaultGeneral.serverPort
return ServerConfigGeneral {..}
parseJSON _ = mzero
| null | https://raw.githubusercontent.com/ds-wizard/engine-backend/12717256cde8d20020e30cd55dc3ef00fef9362a/engine-registry/src/Registry/Model/Config/ServerConfigJM.hs | haskell | module Registry.Model.Config.ServerConfigJM where
import Control.Monad
import Data.Aeson
import Registry.Model.Config.ServerConfig
import Registry.Model.Config.ServerConfigDM
import Shared.Model.Config.EnvironmentJM ()
import Shared.Model.Config.ServerConfigDM
import Shared.Model.Config.ServerConfigJM ()
instance FromJSON ServerConfig where
parseJSON (Object o) = do
general <- o .: "general"
database <- o .:? "database" .!= defaultDatabase
s3 <- o .:? "s3" .!= defaultS3
analytics <- o .:? "analytics" .!= defaultAnalytics
sentry <- o .:? "sentry" .!= defaultSentry
logging <- o .:? "logging" .!= defaultLogging
cloud <- o .:? "cloud" .!= defaultCloud
return ServerConfig {..}
parseJSON _ = mzero
instance FromJSON ServerConfigGeneral where
parseJSON (Object o) = do
environment <- o .:? "environment" .!= defaultGeneral.environment
clientUrl <- o .: "clientUrl"
serverPort <- o .:? "serverPort" .!= defaultGeneral.serverPort
return ServerConfigGeneral {..}
parseJSON _ = mzero
| |
a5ae7a45ab9f80d65ff60efbfc20ae77104af86387d8929b12273d97d52ca217 | Toeplitz/haskell | Well.hs | Parsing checkshot data exported from Petrel
--
--
module Well where
import Text.ParserCombinators.Parsec
data Well = Well { wellX :: Float
, wellY :: Float
, wellZ :: Float
, wellTWT :: Float
, wellMD :: Float
, wellName :: String
} deriving Show
getWellX :: [Well] -> String -> [Well]
getWellX xs name = filter (\x -> wellName x == name) xs
plainValue :: Parser String
plainValue = many (noneOf " \n")
quotedValue :: Parser String
quotedValue = do
_ <- char '"'
content <- many (noneOf "\"")
_ <- char '"'
return content
wellLine :: Parser Well
wellLine = do
x <- plainValue
spaces
y <- plainValue
spaces
z <- plainValue
spaces
twt <- plainValue
spaces
md <- plainValue
spaces
name <- quotedValue
return $ Well (read x) (read y) (read z) (read twt) (read md) name
--wellParse :: String -> IO ()
wellParse = undefined
--wellParse input = case parse wellLine "(test)" input of
-- Left err -> []
-- Right res -> res
| null | https://raw.githubusercontent.com/Toeplitz/haskell/b686aff73033db5f77b7bc2ddc7478a4311f69d9/Well.hs | haskell |
wellParse :: String -> IO ()
wellParse input = case parse wellLine "(test)" input of
Left err -> []
Right res -> res | Parsing checkshot data exported from Petrel
module Well where
import Text.ParserCombinators.Parsec
data Well = Well { wellX :: Float
, wellY :: Float
, wellZ :: Float
, wellTWT :: Float
, wellMD :: Float
, wellName :: String
} deriving Show
getWellX :: [Well] -> String -> [Well]
getWellX xs name = filter (\x -> wellName x == name) xs
plainValue :: Parser String
plainValue = many (noneOf " \n")
quotedValue :: Parser String
quotedValue = do
_ <- char '"'
content <- many (noneOf "\"")
_ <- char '"'
return content
wellLine :: Parser Well
wellLine = do
x <- plainValue
spaces
y <- plainValue
spaces
z <- plainValue
spaces
twt <- plainValue
spaces
md <- plainValue
spaces
name <- quotedValue
return $ Well (read x) (read y) (read z) (read twt) (read md) name
wellParse = undefined
|
ab0f5ff698c9502feca854e2ebbc312ce291d8cba036c83ded6e1701cbd4e523 | ntestoc3/burp-clj | helper_test.clj | (ns burp-clj.helper-test
(:require [burp-clj.helper :refer :all]
[clojure.test :refer :all]))
(deftest http-req-resp-test
(testing "get-full-host"
(is (= ""
(get-full-host {:host "bing.com"
:port 80
:protocol "http"})))
(is (= ""
(get-full-host {:host "bing.com"
:port 443
:protocol "https"})))
(is (= ":2443"
(get-full-host {:host "bing.com"
:port 2443
:protocol "https"})))
(is (= ":8080"
(get-full-host {:host "bing.com"
:port 8080
:protocol "http"}))))
)
| null | https://raw.githubusercontent.com/ntestoc3/burp-clj/436802d34fb77e183cf513ba767e3310d96f6946/test/burp_clj/helper_test.clj | clojure | (ns burp-clj.helper-test
(:require [burp-clj.helper :refer :all]
[clojure.test :refer :all]))
(deftest http-req-resp-test
(testing "get-full-host"
(is (= ""
(get-full-host {:host "bing.com"
:port 80
:protocol "http"})))
(is (= ""
(get-full-host {:host "bing.com"
:port 443
:protocol "https"})))
(is (= ":2443"
(get-full-host {:host "bing.com"
:port 2443
:protocol "https"})))
(is (= ":8080"
(get-full-host {:host "bing.com"
:port 8080
:protocol "http"}))))
)
| |
3af8d14ecb2b6574ffd66ee349925e5ca5ce8995a80b434e5bfc4e81e999928e | DaMSL/K3 | Operator.hs | # LANGUAGE ScopedTypeVariables #
{-# LANGUAGE NoMonoLocalBinds #-}
module Language.K3.Parser.Operator where
import Control.Applicative
import Text.Parser.Combinators
import Text.Parser.Expression hiding ( buildExpressionParser )
import Language.K3.Core.Annotation
import Language.K3.Core.Expression
import qualified Language.K3.Core.Constructor.Expression as EC
import Language.K3.Parser.DataTypes
Operators
uidTagBinOp :: K3Parser (a -> b -> K3 Expression)
-> K3Parser (a -> b -> K3 Expression)
uidTagBinOp mg = (\g uid x y -> g x y @+ EUID uid) <$> mg <*> nextUID
uidTagUnOp :: K3Parser (a -> K3 Expression)
-> K3Parser (a -> K3 Expression)
uidTagUnOp mg = (\g uid x -> g x @+ EUID uid) <$> mg <*> nextUID
binary :: String -> K3BinaryOperator -> Assoc -> (String -> K3Parser ())
-> ParserOperator (K3 Expression)
binary op cstr assoc parser = Infix (uidTagBinOp $ (pure cstr) <* parser op) assoc
prefix :: String -> K3UnaryOperator -> (String -> K3Parser ())
-> ParserOperator (K3 Expression)
prefix op cstr parser = Prefix (uidTagUnOp $ (pure cstr) <* parser op)
Note : unused
postfix : : String - > K3UnaryOperator - > ( String - > K3Parser ( ) )
- > ParserOperator ( K3 Expression )
postfix op cstr parser = Postfix ( uidTagUnOp $ ( pure cstr ) < * parser op )
postfix :: String -> K3UnaryOperator -> (String -> K3Parser ())
-> ParserOperator (K3 Expression)
postfix op cstr parser = Postfix (uidTagUnOp $ (pure cstr) <* parser op)
-}
binaryParseOp :: (String, K3Operator)
-> ((String -> K3Parser ()) -> ParserOperator (K3 Expression))
binaryParseOp (opName, opTag) = binary opName (binOpSpan $ EC.binop opTag) AssocLeft
unaryParseOp :: (String, K3Operator)
-> ((String -> K3Parser ()) -> ParserOperator (K3 Expression))
unaryParseOp (opName, opTag) = prefix opName (unOpSpan opName $ EC.unop opTag)
mkBinOp :: (String, K3Operator) -> ParserOperator (K3 Expression)
mkBinOp x = binaryParseOp x operator
mkBinOpK :: (String, K3Operator) -> ParserOperator (K3 Expression)
mkBinOpK x = binaryParseOp x keyword
mkUnOp :: (String, K3Operator) -> ParserOperator (K3 Expression)
mkUnOp x = unaryParseOp x operator
mkUnOpK :: (String, K3Operator) -> ParserOperator (K3 Expression)
mkUnOpK x = unaryParseOp x keyword
nonSeqOpTable :: OperatorTable K3Parser (K3 Expression)
nonSeqOpTable =
[ map mkUnOp [("-", ONeg)],
map mkBinOp [("*", OMul), ("/", ODiv), ("%", OMod)],
map mkBinOp [("+", OAdd), ("-", OSub)],
map mkBinOp [("++", OConcat)],
map mkBinOp [("<", OLth), ("<=", OLeq), (">", OGth), (">=", OGeq) ],
map mkBinOp [("==", OEqu), ("!=", ONeq), ("<>", ONeq)],
map mkUnOpK [("not", ONot)],
map mkBinOpK [("and", OAnd)],
map mkBinOpK [("or", OOr)]
]
fullOpTable :: OperatorTable K3Parser (K3 Expression)
fullOpTable = nonSeqOpTable ++
[ map mkBinOp [(";", OSeq)]
]
| Duplicate implementation of adopted from the parsers-0.10 source .
-- This applies a bugfix for detecting ambiguous operators.
buildExpressionParser :: forall m a. (Parsing m, Applicative m)
=> OperatorTable m a -> m a -> m a
buildExpressionParser operators simpleExpr
= foldl makeParser simpleExpr operators
where
makeParser term ops
= let (rassoc,lassoc,nassoc,prefix',postfix') = foldr splitOp ([],[],[],[],[]) ops
rassocOp = choice rassoc
lassocOp = choice lassoc
nassocOp = choice nassoc
prefixOp = choice prefix' <?> ""
postfixOp = choice postfix' <?> ""
Note : parsers-0.10 does not employ a ' try ' parser here .
-- ambiguous :: Parsing m => forall c d. String -> m c -> m d
ambiguous assoc op = try $ op *> empty <?> ("ambiguous use of a " ++ assoc ++ "-associative operator")
-- ambiguousRight :: forall a. m a
ambiguousRight = ambiguous "right" rassocOp
-- ambiguousLeft :: forall a. m a
ambiguousLeft = ambiguous "left" lassocOp
-- ambiguousNon :: forall a. m a
ambiguousNon = ambiguous "non" nassocOp
termP = (prefixP <*> term) <**> postfixP
postfixP = postfixOp <|> pure id
prefixP = prefixOp <|> pure id
rassocP, rassocP1, lassocP, lassocP1, nassocP :: m (a -> a)
rassocP = (flip <$> rassocOp <*> (termP <**> rassocP1)
<|> ambiguousLeft
<|> ambiguousNon)
rassocP1 = rassocP <|> pure id
lassocP = ((flip <$> lassocOp <*> termP) <**> ((.) <$> lassocP1)
<|> ambiguousRight
<|> ambiguousNon)
lassocP1 = lassocP <|> pure id
nassocP = (flip <$> nassocOp <*> termP)
<**> (ambiguousRight
<|> ambiguousLeft
<|> ambiguousNon
<|> pure id)
in termP <**> (rassocP <|> lassocP <|> nassocP <|> pure id) <?> "operator"
splitOp (Infix op assoc) (rassoc,lassoc,nassoc,prefix',postfix')
= case assoc of
AssocNone -> (rassoc,lassoc,op:nassoc,prefix',postfix')
AssocLeft -> (rassoc,op:lassoc,nassoc,prefix',postfix')
AssocRight -> (op:rassoc,lassoc,nassoc,prefix',postfix')
splitOp (Prefix op) (rassoc,lassoc,nassoc,prefix',postfix')
= (rassoc,lassoc,nassoc,op:prefix',postfix')
splitOp (Postfix op) (rassoc,lassoc,nassoc,prefix',postfix')
= (rassoc,lassoc,nassoc,prefix',op:postfix')
| null | https://raw.githubusercontent.com/DaMSL/K3/51749157844e76ae79dba619116fc5ad9d685643/src/Language/K3/Parser/Operator.hs | haskell | # LANGUAGE NoMonoLocalBinds #
This applies a bugfix for detecting ambiguous operators.
ambiguous :: Parsing m => forall c d. String -> m c -> m d
ambiguousRight :: forall a. m a
ambiguousLeft :: forall a. m a
ambiguousNon :: forall a. m a | # LANGUAGE ScopedTypeVariables #
module Language.K3.Parser.Operator where
import Control.Applicative
import Text.Parser.Combinators
import Text.Parser.Expression hiding ( buildExpressionParser )
import Language.K3.Core.Annotation
import Language.K3.Core.Expression
import qualified Language.K3.Core.Constructor.Expression as EC
import Language.K3.Parser.DataTypes
Operators
uidTagBinOp :: K3Parser (a -> b -> K3 Expression)
-> K3Parser (a -> b -> K3 Expression)
uidTagBinOp mg = (\g uid x y -> g x y @+ EUID uid) <$> mg <*> nextUID
uidTagUnOp :: K3Parser (a -> K3 Expression)
-> K3Parser (a -> K3 Expression)
uidTagUnOp mg = (\g uid x -> g x @+ EUID uid) <$> mg <*> nextUID
binary :: String -> K3BinaryOperator -> Assoc -> (String -> K3Parser ())
-> ParserOperator (K3 Expression)
binary op cstr assoc parser = Infix (uidTagBinOp $ (pure cstr) <* parser op) assoc
prefix :: String -> K3UnaryOperator -> (String -> K3Parser ())
-> ParserOperator (K3 Expression)
prefix op cstr parser = Prefix (uidTagUnOp $ (pure cstr) <* parser op)
Note : unused
postfix : : String - > K3UnaryOperator - > ( String - > K3Parser ( ) )
- > ParserOperator ( K3 Expression )
postfix op cstr parser = Postfix ( uidTagUnOp $ ( pure cstr ) < * parser op )
postfix :: String -> K3UnaryOperator -> (String -> K3Parser ())
-> ParserOperator (K3 Expression)
postfix op cstr parser = Postfix (uidTagUnOp $ (pure cstr) <* parser op)
-}
binaryParseOp :: (String, K3Operator)
-> ((String -> K3Parser ()) -> ParserOperator (K3 Expression))
binaryParseOp (opName, opTag) = binary opName (binOpSpan $ EC.binop opTag) AssocLeft
unaryParseOp :: (String, K3Operator)
-> ((String -> K3Parser ()) -> ParserOperator (K3 Expression))
unaryParseOp (opName, opTag) = prefix opName (unOpSpan opName $ EC.unop opTag)
mkBinOp :: (String, K3Operator) -> ParserOperator (K3 Expression)
mkBinOp x = binaryParseOp x operator
mkBinOpK :: (String, K3Operator) -> ParserOperator (K3 Expression)
mkBinOpK x = binaryParseOp x keyword
mkUnOp :: (String, K3Operator) -> ParserOperator (K3 Expression)
mkUnOp x = unaryParseOp x operator
mkUnOpK :: (String, K3Operator) -> ParserOperator (K3 Expression)
mkUnOpK x = unaryParseOp x keyword
nonSeqOpTable :: OperatorTable K3Parser (K3 Expression)
nonSeqOpTable =
[ map mkUnOp [("-", ONeg)],
map mkBinOp [("*", OMul), ("/", ODiv), ("%", OMod)],
map mkBinOp [("+", OAdd), ("-", OSub)],
map mkBinOp [("++", OConcat)],
map mkBinOp [("<", OLth), ("<=", OLeq), (">", OGth), (">=", OGeq) ],
map mkBinOp [("==", OEqu), ("!=", ONeq), ("<>", ONeq)],
map mkUnOpK [("not", ONot)],
map mkBinOpK [("and", OAnd)],
map mkBinOpK [("or", OOr)]
]
fullOpTable :: OperatorTable K3Parser (K3 Expression)
fullOpTable = nonSeqOpTable ++
[ map mkBinOp [(";", OSeq)]
]
| Duplicate implementation of adopted from the parsers-0.10 source .
buildExpressionParser :: forall m a. (Parsing m, Applicative m)
=> OperatorTable m a -> m a -> m a
buildExpressionParser operators simpleExpr
= foldl makeParser simpleExpr operators
where
makeParser term ops
= let (rassoc,lassoc,nassoc,prefix',postfix') = foldr splitOp ([],[],[],[],[]) ops
rassocOp = choice rassoc
lassocOp = choice lassoc
nassocOp = choice nassoc
prefixOp = choice prefix' <?> ""
postfixOp = choice postfix' <?> ""
Note : parsers-0.10 does not employ a ' try ' parser here .
ambiguous assoc op = try $ op *> empty <?> ("ambiguous use of a " ++ assoc ++ "-associative operator")
ambiguousRight = ambiguous "right" rassocOp
ambiguousLeft = ambiguous "left" lassocOp
ambiguousNon = ambiguous "non" nassocOp
termP = (prefixP <*> term) <**> postfixP
postfixP = postfixOp <|> pure id
prefixP = prefixOp <|> pure id
rassocP, rassocP1, lassocP, lassocP1, nassocP :: m (a -> a)
rassocP = (flip <$> rassocOp <*> (termP <**> rassocP1)
<|> ambiguousLeft
<|> ambiguousNon)
rassocP1 = rassocP <|> pure id
lassocP = ((flip <$> lassocOp <*> termP) <**> ((.) <$> lassocP1)
<|> ambiguousRight
<|> ambiguousNon)
lassocP1 = lassocP <|> pure id
nassocP = (flip <$> nassocOp <*> termP)
<**> (ambiguousRight
<|> ambiguousLeft
<|> ambiguousNon
<|> pure id)
in termP <**> (rassocP <|> lassocP <|> nassocP <|> pure id) <?> "operator"
splitOp (Infix op assoc) (rassoc,lassoc,nassoc,prefix',postfix')
= case assoc of
AssocNone -> (rassoc,lassoc,op:nassoc,prefix',postfix')
AssocLeft -> (rassoc,op:lassoc,nassoc,prefix',postfix')
AssocRight -> (op:rassoc,lassoc,nassoc,prefix',postfix')
splitOp (Prefix op) (rassoc,lassoc,nassoc,prefix',postfix')
= (rassoc,lassoc,nassoc,op:prefix',postfix')
splitOp (Postfix op) (rassoc,lassoc,nassoc,prefix',postfix')
= (rassoc,lassoc,nassoc,prefix',op:postfix')
|
3c80e203d61c9cca180d4bbe892294a2a9435c5f8ff2107167880e0d1d2dac98 | Mbodin/murder-generator | attribute.mli | (** odule Attribute
Describes the player and contact attributes used thorough this development. *)
(** A signature for the various attribute/constructor structures.
This signature is used in particular for the player attributes and the contact
attributes. *)
module type Attribute = sig
(** The type of attributes. *)
type attribute
(** The type of constructors. *)
type constructor
(** Values are just constructor identifiers.
Each attribute is associated with a given set of possible constructors
(which are really just names).
The following table keeps track of the constructor names. *)
type constructor_map
(** An empty constructor map. *)
val empty_constructor_map : constructor_map
(** Return the name of an attribute. *)
val attribute_name : constructor_map -> attribute -> string option
(** Return the name of a constructor. *)
val constructor_name : constructor_map -> constructor -> string option
(** Return the associated attribute of a constructor. *)
val constructor_attribute : constructor_map -> constructor -> attribute option
(** Return the list of constructors associated to an attribute. *)
val constructors : constructor_map -> attribute -> constructor list option
(** Returns all defined constructors. *)
val all_constructors : constructor_map -> constructor list
(** Declare an attribute, returning its associated normal identifier.
The string is the name of the attribute and the boolean states whether
it is internal.
If already declared, its previously-set identifier is still returned,
but its internal status is updated. *)
val declare_attribute : constructor_map -> string -> bool -> attribute * constructor_map
(** Declare a new constructor for an attribute.
The string is the name of the constructor and the boolean states whether
it is internal.
If already declared, its previously-set identifier is still returned,
but its internal status is updated. *)
val declare_constructor : constructor_map -> attribute -> string -> bool -> constructor * constructor_map
(** Get the attribute identifier from its name. *)
val get_attribute : constructor_map -> string -> attribute option
(** Get the constructor identifier from its attribute and its name. *)
val get_constructor : constructor_map -> attribute -> string -> constructor option
(** Users can remove categories before the story generation.
This function removes a constructor, probably because it was associated
to an unwanted category. *)
val remove_constructor : constructor_map -> constructor -> constructor_map
* State that the first constructor is compatible with the second .
val declare_compatibility : constructor_map -> attribute -> constructor -> constructor -> constructor_map
* State whether the first constructor is compatible with the second .
val is_compatible : constructor_map -> attribute -> constructor -> constructor -> bool
(** State whether the given constructor is internal. *)
val is_internal : constructor_map -> attribute -> constructor -> bool
end
(** A module to express attributes and constructors for players and objects. *)
module PlayerAttribute : Attribute
(** A module to express attributes and constructors for contacts between players. *)
module ContactAttribute : Attribute
(** This data structure stores all the informations about constructors. *)
type constructor_maps = {
player : PlayerAttribute.constructor_map ;
contact : ContactAttribute.constructor_map
}
(** An empty structure. *)
val empty_constructor_maps : constructor_maps
(** A special internal attribute for objects. *)
val object_type : PlayerAttribute.attribute
(** A generic attribute type for modules who don’t need to precisely
understand how attributes work, merging both kinds of attributes. *)
type attribute =
| PlayerAttribute of PlayerAttribute.attribute
| ContactAttribute of ContactAttribute.attribute
(** Similarly, a generic constructor type. *)
type constructor =
| PlayerConstructor of PlayerAttribute.constructor
| ContactConstructor of ContactAttribute.constructor
| null | https://raw.githubusercontent.com/Mbodin/murder-generator/2024a924ffb4ee12d1b7119b699346b21e098892/src/attribute.mli | ocaml | * odule Attribute
Describes the player and contact attributes used thorough this development.
* A signature for the various attribute/constructor structures.
This signature is used in particular for the player attributes and the contact
attributes.
* The type of attributes.
* The type of constructors.
* Values are just constructor identifiers.
Each attribute is associated with a given set of possible constructors
(which are really just names).
The following table keeps track of the constructor names.
* An empty constructor map.
* Return the name of an attribute.
* Return the name of a constructor.
* Return the associated attribute of a constructor.
* Return the list of constructors associated to an attribute.
* Returns all defined constructors.
* Declare an attribute, returning its associated normal identifier.
The string is the name of the attribute and the boolean states whether
it is internal.
If already declared, its previously-set identifier is still returned,
but its internal status is updated.
* Declare a new constructor for an attribute.
The string is the name of the constructor and the boolean states whether
it is internal.
If already declared, its previously-set identifier is still returned,
but its internal status is updated.
* Get the attribute identifier from its name.
* Get the constructor identifier from its attribute and its name.
* Users can remove categories before the story generation.
This function removes a constructor, probably because it was associated
to an unwanted category.
* State whether the given constructor is internal.
* A module to express attributes and constructors for players and objects.
* A module to express attributes and constructors for contacts between players.
* This data structure stores all the informations about constructors.
* An empty structure.
* A special internal attribute for objects.
* A generic attribute type for modules who don’t need to precisely
understand how attributes work, merging both kinds of attributes.
* Similarly, a generic constructor type. |
module type Attribute = sig
type attribute
type constructor
type constructor_map
val empty_constructor_map : constructor_map
val attribute_name : constructor_map -> attribute -> string option
val constructor_name : constructor_map -> constructor -> string option
val constructor_attribute : constructor_map -> constructor -> attribute option
val constructors : constructor_map -> attribute -> constructor list option
val all_constructors : constructor_map -> constructor list
val declare_attribute : constructor_map -> string -> bool -> attribute * constructor_map
val declare_constructor : constructor_map -> attribute -> string -> bool -> constructor * constructor_map
val get_attribute : constructor_map -> string -> attribute option
val get_constructor : constructor_map -> attribute -> string -> constructor option
val remove_constructor : constructor_map -> constructor -> constructor_map
* State that the first constructor is compatible with the second .
val declare_compatibility : constructor_map -> attribute -> constructor -> constructor -> constructor_map
* State whether the first constructor is compatible with the second .
val is_compatible : constructor_map -> attribute -> constructor -> constructor -> bool
val is_internal : constructor_map -> attribute -> constructor -> bool
end
module PlayerAttribute : Attribute
module ContactAttribute : Attribute
type constructor_maps = {
player : PlayerAttribute.constructor_map ;
contact : ContactAttribute.constructor_map
}
val empty_constructor_maps : constructor_maps
val object_type : PlayerAttribute.attribute
type attribute =
| PlayerAttribute of PlayerAttribute.attribute
| ContactAttribute of ContactAttribute.attribute
type constructor =
| PlayerConstructor of PlayerAttribute.constructor
| ContactConstructor of ContactAttribute.constructor
|
bebaa932d1c05a89ac797ee0e9a3ae6d453584000c97d42a21f5f65d157d7741 | jacquev6/DrawGrammar | Lex.ml | open General.Abbr
let unescape s =
@todo Use General . String.replace_all when it 's implemented
s
|> Str.split ~sep:"\\ "
|> StrLi.join ~sep:" "
|> Str.split ~sep:"\\-"
|> StrLi.join ~sep:"-"
| null | https://raw.githubusercontent.com/jacquev6/DrawGrammar/ee056a086ca0d8b18889fa06883287fda84807c3/src/Lex.ml | ocaml | open General.Abbr
let unescape s =
@todo Use General . String.replace_all when it 's implemented
s
|> Str.split ~sep:"\\ "
|> StrLi.join ~sep:" "
|> Str.split ~sep:"\\-"
|> StrLi.join ~sep:"-"
| |
eb640c092b351240611daefa505036c71c66b0e3a6f1608357b5be93699d02b8 | leonoel/missionary | sem_test.cljc | (ns missionary.sem-test
(:require [lolcat.core :as lc]
[lolcat.lib :as l]
[missionary.core :as m]
[clojure.test :as t])
(:import [missionary Cancelled]))
(lc/defword release [id & events] [(l/dup) (l/change get id) (apply lc/call 0 events) (l/lose)])
(lc/defword acquire [id lock-id & events] [(l/dup) (l/change get id) (apply l/start lock-id events)])
(defn acquired [lock-id] (l/succeeded lock-id nil?))
(t/deftest simple
(t/is (= []
(lc/run
(l/store
(m/sem) (l/insert :sem)
(acquire :sem :lock1 (acquired :lock1))
(acquire :sem :lock2)
(release :sem (acquired :lock2)))))))
(t/deftest more-tokens
(t/is (= []
(lc/run
(l/store
(m/sem 3) (l/insert :sem)
(acquire :sem :lock1 (acquired :lock1))
(acquire :sem :lock2 (acquired :lock2))
(acquire :sem :lock3 (acquired :lock3))
(acquire :sem :lock4)
(release :sem (acquired :lock4)))))))
(t/deftest cancel
(t/is (= []
(lc/run
(l/store
(m/sem) (l/insert :sem)
(acquire :sem :lock1 (acquired :lock1))
(acquire :sem :lock2)
(l/cancel :lock2 (l/failed :lock2 (partial instance? Cancelled))))))))
(defn sem
([] (lc/event :released))
([s _f] (s (lc/event :acquired))))
(t/deftest holding
(t/is (= []
(lc/run
(l/store
(m/sp (m/holding sem (lc/event :return-event)))
(l/start :main
(l/compose (l/check #{:acquired}) nil)
(l/compose (l/check #{:return-event}) :val)
(l/compose (l/check #{:released}) nil)
(l/succeeded :main #{:val})))))))
| null | https://raw.githubusercontent.com/leonoel/missionary/848903be20d8c301462c2f5d9d4ef29b2d50b158/test/missionary/sem_test.cljc | clojure | (ns missionary.sem-test
(:require [lolcat.core :as lc]
[lolcat.lib :as l]
[missionary.core :as m]
[clojure.test :as t])
(:import [missionary Cancelled]))
(lc/defword release [id & events] [(l/dup) (l/change get id) (apply lc/call 0 events) (l/lose)])
(lc/defword acquire [id lock-id & events] [(l/dup) (l/change get id) (apply l/start lock-id events)])
(defn acquired [lock-id] (l/succeeded lock-id nil?))
(t/deftest simple
(t/is (= []
(lc/run
(l/store
(m/sem) (l/insert :sem)
(acquire :sem :lock1 (acquired :lock1))
(acquire :sem :lock2)
(release :sem (acquired :lock2)))))))
(t/deftest more-tokens
(t/is (= []
(lc/run
(l/store
(m/sem 3) (l/insert :sem)
(acquire :sem :lock1 (acquired :lock1))
(acquire :sem :lock2 (acquired :lock2))
(acquire :sem :lock3 (acquired :lock3))
(acquire :sem :lock4)
(release :sem (acquired :lock4)))))))
(t/deftest cancel
(t/is (= []
(lc/run
(l/store
(m/sem) (l/insert :sem)
(acquire :sem :lock1 (acquired :lock1))
(acquire :sem :lock2)
(l/cancel :lock2 (l/failed :lock2 (partial instance? Cancelled))))))))
(defn sem
([] (lc/event :released))
([s _f] (s (lc/event :acquired))))
(t/deftest holding
(t/is (= []
(lc/run
(l/store
(m/sp (m/holding sem (lc/event :return-event)))
(l/start :main
(l/compose (l/check #{:acquired}) nil)
(l/compose (l/check #{:return-event}) :val)
(l/compose (l/check #{:released}) nil)
(l/succeeded :main #{:val})))))))
| |
1a2c4cf26fa66c20b8a565cb2aef29b41337680b52ed7bb88a8307f4683fbbfb | locusmath/locus | object.clj | (ns locus.order.join-semilattice.element.object
(:require [locus.set.logic.core.set :refer :all]
[locus.set.logic.limit.product :refer :all]
[locus.con.core.setpart :refer :all]
[locus.set.mapping.general.core.object :refer :all]
[locus.set.logic.structure.protocols :refer :all]
[locus.set.copresheaf.structure.core.protocols :refer :all]
[locus.set.quiver.binary.core.object :refer :all]
[locus.order.general.core.object :refer :all]
[locus.order.join-semilattice.core.object :refer :all]
[locus.set.quiver.structure.core.protocols :refer :all])
(:import (locus.order.join_semilattice.core.object JoinSemilattice)))
; An object of a thin category having all binary coproducts
(deftype JoinSemilatticeObject
[lattice elem]
Element
(parent [this] lattice)
SectionElement
(tag [this] 1)
(member [this] elem)
IdentifiableInstance
(unwrap [this] elem))
(derive JoinSemilatticeObject :locus.set.logic.structure.protocols/element)
(defmethod wrap JoinSemilattice
[^JoinSemilattice source, x]
(JoinSemilatticeObject. source x))
; Coproducts of objects in join semilattices
(defmethod coproduct JoinSemilatticeObject
[& objects]
(let [current-join-semilattice (parent (first objects))]
(JoinSemilatticeObject.
current-join-semilattice
(apply
(join-fn current-join-semilattice)
(map #(.elem %) objects)))))
; Ontology of join semilattice elements
(defn join-semilattice-element?
[x]
(= (type x) JoinSemilatticeObject)) | null | https://raw.githubusercontent.com/locusmath/locus/fb6068bd78977b51fd3c5783545a5f9986e4235c/src/clojure/locus/order/join_semilattice/element/object.clj | clojure | An object of a thin category having all binary coproducts
Coproducts of objects in join semilattices
Ontology of join semilattice elements | (ns locus.order.join-semilattice.element.object
(:require [locus.set.logic.core.set :refer :all]
[locus.set.logic.limit.product :refer :all]
[locus.con.core.setpart :refer :all]
[locus.set.mapping.general.core.object :refer :all]
[locus.set.logic.structure.protocols :refer :all]
[locus.set.copresheaf.structure.core.protocols :refer :all]
[locus.set.quiver.binary.core.object :refer :all]
[locus.order.general.core.object :refer :all]
[locus.order.join-semilattice.core.object :refer :all]
[locus.set.quiver.structure.core.protocols :refer :all])
(:import (locus.order.join_semilattice.core.object JoinSemilattice)))
(deftype JoinSemilatticeObject
[lattice elem]
Element
(parent [this] lattice)
SectionElement
(tag [this] 1)
(member [this] elem)
IdentifiableInstance
(unwrap [this] elem))
(derive JoinSemilatticeObject :locus.set.logic.structure.protocols/element)
(defmethod wrap JoinSemilattice
[^JoinSemilattice source, x]
(JoinSemilatticeObject. source x))
(defmethod coproduct JoinSemilatticeObject
[& objects]
(let [current-join-semilattice (parent (first objects))]
(JoinSemilatticeObject.
current-join-semilattice
(apply
(join-fn current-join-semilattice)
(map #(.elem %) objects)))))
(defn join-semilattice-element?
[x]
(= (type x) JoinSemilatticeObject)) |
4ec0bfb003f4c2a2559a4f199a85c0018593af31083dfa2e6d89fbb1c9787b1c | adamschoenemann/clofrp | Type.hs |
# LANGUAGE DeriveFunctor #
# LANGUAGE NamedFieldPuns #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeSynonymInstances #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GADTs #-}
# LANGUAGE ViewPatterns #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE DataKinds #
# LANGUAGE KindSignatures #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ExistentialQuantification #
# LANGUAGE AllowAmbiguousTypes #
# LANGUAGE StandaloneDeriving #
# LANGUAGE DeriveGeneric #
{-# LANGUAGE DeriveAnyClass #-}
module CloFRP.AST.Type where
import Data.String (IsString(..))
import qualified Data.Set as S
import Data.Data (Data, Typeable)
import Data.Char (isUpper)
import CloFRP.Pretty
import Control.DeepSeq
import CloFRP.Annotated
import CloFRP.AST.Name
import CloFRP.AST.Kind
import CloFRP.AST.Utils
type Type a s = Annotated a (Type' a s)
data TySort = Mono | Poly deriving (Show, Eq)
data Type' :: * -> TySort -> * where
ℱ
TVar :: Name -> Type' a s -- x
TExists :: Name -> Type' a s -- α^
F B
(:->:) :: Type a s -> Type a s -> Type' a s -- A -> B
Forall :: Name -> Kind -> Type a 'Poly -> Type' a 'Poly -- ∀(α : χ). A
RecTy :: Type a s -> Type' a s -- Fix F
TTuple :: [Type a s] -> Type' a s -- ⟨A₁,...,Aₙ⟩
Later :: Type a s -> Type a s -> Type' a s -- ⊳k A
type PolyType a = Type a 'Poly
type MonoType a = Type a 'Mono
deriving instance Eq a => Eq (Type' a s)
deriving instance Data a => Data (Type' a 'Poly)
deriving instance Typeable a => Typeable (Type' a 'Poly)
-- deriving instance Show a => Show (Type' a s)
instance NFData a => NFData (Type' a 'Poly) where
rnf a = seq a ()
prettyBound :: Bool -> Name -> Kind -> Doc ann
prettyBound _ nm Star = pretty nm
prettyBound p nm k = (if p then parens else id) $ pretty nm <+> ":" <+> pretty k
prettyT' :: Bool -> Type' a s -> Doc ann
prettyT' pars = \case
TFree n -> fromString . show $ n
TVar n -> fromString . show $ n
TExists n -> "∃" <> fromString (show n)
TApp x y -> parensIf $ prettyT False x <+> prettyT True y
x :->: y -> parensIf $ prettyT True x <> softline <> "->" <+> prettyT False y
Forall n k t ->
let (ns, t') = collect p t
bound = hsep $ map (uncurry $ prettyBound True) ((n,k):ns)
in parensIf $ "∀" <> bound <> dot <+> prettyT False t'
where
p :: Type' a s -> Maybe ((Name, Kind), Type a s)
p (Forall n' k' t') = Just ((n', k'), t')
p _ = Nothing
RecTy t -> parensIf $ "Fix" <+> prettyT True t
TTuple ts -> tupled $ map (prettyT False) ts
Later t1 t2 -> parensIf $ "⊳" <> prettyT True t1 <+> prettyT True t2
where
parensIf = if pars then parens else id
prettyT :: Bool -> Type a s -> Doc ann
prettyT n (A _ t) = prettyT' n t
instance Pretty (Type' a s) where
pretty = prettyT' False
instance Pretty (Type a s) where
pretty (A _ t) = prettyT' False t
instance Show (Type' a s) where
show = ppsw 1000
instance Unann (Type a s) (Type () s) where
unann = unannT
unannT :: Type a s -> Type () s
unannT (A _ t) = A () $ unannT' t
instance Unann (Type' a s) (Type' () s) where
unann = unannT'
unannT' :: Type' a s -> Type' () s
unannT' = \case
TFree x -> TFree x
TVar x -> TVar x
TExists x -> TExists x
t1 `TApp` t2 -> unannT t1 `TApp` unannT t2
t1 :->: t2 -> unannT t1 :->: unannT t2
Forall nm k tau -> Forall nm k (unannT tau)
RecTy tau -> RecTy (unannT tau)
TTuple ts -> TTuple (map unannT ts)
Later x t -> Later (unannT x) (unannT t)
nameToType' :: Name -> Type' a s
nameToType' nm@(UName (c:_)) | isUpper c = TFree nm
nameToType' nm = TVar nm
nameToType :: a -> Name -> Type a s
nameToType ann = A ann . nameToType'
nameToExistential' :: Name -> Type' a s
nameToExistential' nm@(UName (c:_)) | isUpper c = TFree nm
nameToExistential' nm = TExists nm
instance IsString (Type () s) where
fromString s = nameToType () (UName s)
infixl 9 @@:
(@@:) :: Type () 'Poly -> Type () 'Poly -> Type () 'Poly
a @@: b = A () $ a `TApp` b
infixr 2 @->:
(@->:) :: Type () s -> Type () s -> Type () s
a @->: b = A () $ a :->: b
-- alphaEquiv :: Type a s -> Type b s -> Bool
-- alphaEquiv t1 t2 = go (unann t1) (unann t2) 0 where
-- go (A _ t1') (A _ t2') =
-- case (t1', t2') of
( TFree n1 , ) - > n1 = = n2
( TVar n1 , TVar n2 ) - > n1 = = n2
-- TVar n -> S.singleton n
-- TExists n -> S.singleton n
-- TApp x y -> freeVars x `S.union` freeVars y
x :-> : freeVars x ` S.union ` freeVars y
-- Forall n k t -> freeVars t `S.difference` S.singleton n
-- RecTy t -> freeVars t
-- TTuple ts -> S.unions $ map freeVars ts
-- Later t1 t2 -> freeVars t1 `S.union` freeVars t2
freeVars :: Type a s -> S.Set Name
freeVars (A _ ty) =
case ty of
TFree n -> S.singleton n
TVar n -> S.singleton n
TExists n -> S.singleton n
TApp x y -> freeVars x `S.union` freeVars y
x :->: y -> freeVars x `S.union` freeVars y
Forall n _k t -> freeVars t `S.difference` S.singleton n
RecTy t -> freeVars t
TTuple ts -> S.unions $ map freeVars ts
Later t1 t2 -> freeVars t1 `S.union` freeVars t2
inFreeVars :: Name -> Type a s -> Bool
inFreeVars nm t = nm `S.member` freeVars t
asPolytype :: Type a s -> PolyType a
asPolytype (A a ty) = A a $
case ty of
TFree x -> TFree x
TVar x -> TVar x
TExists x -> TExists x
t1 `TApp` t2 -> asPolytype t1 `TApp` asPolytype t2
t1 :->: t2 -> asPolytype t1 :->: asPolytype t2
Forall x k t -> Forall x k (asPolytype t)
RecTy t -> RecTy (asPolytype t)
TTuple ts -> TTuple (map asPolytype ts)
Later t1 t2 -> Later (asPolytype t1) (asPolytype t2)
asMonotype :: Type a s -> Maybe (MonoType a)
asMonotype (A a ty) =
case ty of
TFree x -> pure (A a $ TFree x)
TVar x -> pure (A a $ TVar x)
TExists x -> pure (A a $ TExists x)
t1 `TApp` t2 -> (\x y -> A a $ TApp x y) <$> asMonotype t1 <*> asMonotype t2
t1 :->: t2 -> (\x y -> A a (x :->: y)) <$> asMonotype t1 <*> asMonotype t2
Forall _ _ _ -> Nothing
RecTy t -> A a . RecTy <$> asMonotype t
TTuple ts -> A a . TTuple <$> sequence (map asMonotype ts)
Later t1 t2 -> (\x y -> A a $ Later x y) <$> asMonotype t1 <*> asMonotype t2
subst :: PolyType a -> Name -> PolyType a -> PolyType a
subst x forY (A a inTy) =
case inTy of
TFree y | y == forY -> x
| otherwise -> A a $ TFree y
TVar y | y == forY -> x
| otherwise -> A a $ TVar y
TExists y | y == forY -> x
| otherwise -> A a $ TExists y
Forall y k t | y == forY -> A a $ Forall y k t
| otherwise -> A a $ Forall y k (subst x forY t)
-- TODO: OK, this is a nasty hack to substitute clock variables
-- will only really work as long as clock variables and type variables do not
-- share a namespace
Later t1 t2 -> A a (Later (subst x forY t1) (subst x forY t2))
RecTy t -> A a $ RecTy (subst x forY t)
TTuple ts -> A a $ TTuple (map (subst x forY) ts)
t1 `TApp` t2 -> A a $ subst x forY t1 `TApp` subst x forY t2
t1 :->: t2 -> A a $ subst x forY t1 :->: subst x forY t2
-- | Extract the clock-variable from a type
extractKappa :: Type a s -> Either String Name
extractKappa (A _ kv) =
case kv of
TExists k -> pure k
TVar k -> pure k
TFree k -> pure k
TFree " K0 " - > pure " K0 " -- FIXME : K0 Hack
_ -> Left $ show $ "Expected clock variable but got" <+> pretty kv
| null | https://raw.githubusercontent.com/adamschoenemann/clofrp/c26f86aec2cdb8fa7fd317acd13f7d77af984bd3/library/CloFRP/AST/Type.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE TypeSynonymInstances #
# LANGUAGE DeriveDataTypeable #
# LANGUAGE GADTs #
# LANGUAGE RankNTypes #
# LANGUAGE DeriveAnyClass #
x
α^
A -> B
∀(α : χ). A
Fix F
⟨A₁,...,Aₙ⟩
⊳k A
deriving instance Show a => Show (Type' a s)
alphaEquiv :: Type a s -> Type b s -> Bool
alphaEquiv t1 t2 = go (unann t1) (unann t2) 0 where
go (A _ t1') (A _ t2') =
case (t1', t2') of
TVar n -> S.singleton n
TExists n -> S.singleton n
TApp x y -> freeVars x `S.union` freeVars y
Forall n k t -> freeVars t `S.difference` S.singleton n
RecTy t -> freeVars t
TTuple ts -> S.unions $ map freeVars ts
Later t1 t2 -> freeVars t1 `S.union` freeVars t2
TODO: OK, this is a nasty hack to substitute clock variables
will only really work as long as clock variables and type variables do not
share a namespace
| Extract the clock-variable from a type
FIXME : K0 Hack |
# LANGUAGE DeriveFunctor #
# LANGUAGE NamedFieldPuns #
# LANGUAGE LambdaCase #
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE ViewPatterns #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE DataKinds #
# LANGUAGE KindSignatures #
# LANGUAGE ExistentialQuantification #
# LANGUAGE AllowAmbiguousTypes #
# LANGUAGE StandaloneDeriving #
# LANGUAGE DeriveGeneric #
module CloFRP.AST.Type where
import Data.String (IsString(..))
import qualified Data.Set as S
import Data.Data (Data, Typeable)
import Data.Char (isUpper)
import CloFRP.Pretty
import Control.DeepSeq
import CloFRP.Annotated
import CloFRP.AST.Name
import CloFRP.AST.Kind
import CloFRP.AST.Utils
type Type a s = Annotated a (Type' a s)
data TySort = Mono | Poly deriving (Show, Eq)
data Type' :: * -> TySort -> * where
ℱ
F B
type PolyType a = Type a 'Poly
type MonoType a = Type a 'Mono
deriving instance Eq a => Eq (Type' a s)
deriving instance Data a => Data (Type' a 'Poly)
deriving instance Typeable a => Typeable (Type' a 'Poly)
instance NFData a => NFData (Type' a 'Poly) where
rnf a = seq a ()
prettyBound :: Bool -> Name -> Kind -> Doc ann
prettyBound _ nm Star = pretty nm
prettyBound p nm k = (if p then parens else id) $ pretty nm <+> ":" <+> pretty k
prettyT' :: Bool -> Type' a s -> Doc ann
prettyT' pars = \case
TFree n -> fromString . show $ n
TVar n -> fromString . show $ n
TExists n -> "∃" <> fromString (show n)
TApp x y -> parensIf $ prettyT False x <+> prettyT True y
x :->: y -> parensIf $ prettyT True x <> softline <> "->" <+> prettyT False y
Forall n k t ->
let (ns, t') = collect p t
bound = hsep $ map (uncurry $ prettyBound True) ((n,k):ns)
in parensIf $ "∀" <> bound <> dot <+> prettyT False t'
where
p :: Type' a s -> Maybe ((Name, Kind), Type a s)
p (Forall n' k' t') = Just ((n', k'), t')
p _ = Nothing
RecTy t -> parensIf $ "Fix" <+> prettyT True t
TTuple ts -> tupled $ map (prettyT False) ts
Later t1 t2 -> parensIf $ "⊳" <> prettyT True t1 <+> prettyT True t2
where
parensIf = if pars then parens else id
prettyT :: Bool -> Type a s -> Doc ann
prettyT n (A _ t) = prettyT' n t
instance Pretty (Type' a s) where
pretty = prettyT' False
instance Pretty (Type a s) where
pretty (A _ t) = prettyT' False t
instance Show (Type' a s) where
show = ppsw 1000
instance Unann (Type a s) (Type () s) where
unann = unannT
unannT :: Type a s -> Type () s
unannT (A _ t) = A () $ unannT' t
instance Unann (Type' a s) (Type' () s) where
unann = unannT'
unannT' :: Type' a s -> Type' () s
unannT' = \case
TFree x -> TFree x
TVar x -> TVar x
TExists x -> TExists x
t1 `TApp` t2 -> unannT t1 `TApp` unannT t2
t1 :->: t2 -> unannT t1 :->: unannT t2
Forall nm k tau -> Forall nm k (unannT tau)
RecTy tau -> RecTy (unannT tau)
TTuple ts -> TTuple (map unannT ts)
Later x t -> Later (unannT x) (unannT t)
nameToType' :: Name -> Type' a s
nameToType' nm@(UName (c:_)) | isUpper c = TFree nm
nameToType' nm = TVar nm
nameToType :: a -> Name -> Type a s
nameToType ann = A ann . nameToType'
nameToExistential' :: Name -> Type' a s
nameToExistential' nm@(UName (c:_)) | isUpper c = TFree nm
nameToExistential' nm = TExists nm
instance IsString (Type () s) where
fromString s = nameToType () (UName s)
infixl 9 @@:
(@@:) :: Type () 'Poly -> Type () 'Poly -> Type () 'Poly
a @@: b = A () $ a `TApp` b
infixr 2 @->:
(@->:) :: Type () s -> Type () s -> Type () s
a @->: b = A () $ a :->: b
( TFree n1 , ) - > n1 = = n2
( TVar n1 , TVar n2 ) - > n1 = = n2
x :-> : freeVars x ` S.union ` freeVars y
freeVars :: Type a s -> S.Set Name
freeVars (A _ ty) =
case ty of
TFree n -> S.singleton n
TVar n -> S.singleton n
TExists n -> S.singleton n
TApp x y -> freeVars x `S.union` freeVars y
x :->: y -> freeVars x `S.union` freeVars y
Forall n _k t -> freeVars t `S.difference` S.singleton n
RecTy t -> freeVars t
TTuple ts -> S.unions $ map freeVars ts
Later t1 t2 -> freeVars t1 `S.union` freeVars t2
inFreeVars :: Name -> Type a s -> Bool
inFreeVars nm t = nm `S.member` freeVars t
asPolytype :: Type a s -> PolyType a
asPolytype (A a ty) = A a $
case ty of
TFree x -> TFree x
TVar x -> TVar x
TExists x -> TExists x
t1 `TApp` t2 -> asPolytype t1 `TApp` asPolytype t2
t1 :->: t2 -> asPolytype t1 :->: asPolytype t2
Forall x k t -> Forall x k (asPolytype t)
RecTy t -> RecTy (asPolytype t)
TTuple ts -> TTuple (map asPolytype ts)
Later t1 t2 -> Later (asPolytype t1) (asPolytype t2)
asMonotype :: Type a s -> Maybe (MonoType a)
asMonotype (A a ty) =
case ty of
TFree x -> pure (A a $ TFree x)
TVar x -> pure (A a $ TVar x)
TExists x -> pure (A a $ TExists x)
t1 `TApp` t2 -> (\x y -> A a $ TApp x y) <$> asMonotype t1 <*> asMonotype t2
t1 :->: t2 -> (\x y -> A a (x :->: y)) <$> asMonotype t1 <*> asMonotype t2
Forall _ _ _ -> Nothing
RecTy t -> A a . RecTy <$> asMonotype t
TTuple ts -> A a . TTuple <$> sequence (map asMonotype ts)
Later t1 t2 -> (\x y -> A a $ Later x y) <$> asMonotype t1 <*> asMonotype t2
subst :: PolyType a -> Name -> PolyType a -> PolyType a
subst x forY (A a inTy) =
case inTy of
TFree y | y == forY -> x
| otherwise -> A a $ TFree y
TVar y | y == forY -> x
| otherwise -> A a $ TVar y
TExists y | y == forY -> x
| otherwise -> A a $ TExists y
Forall y k t | y == forY -> A a $ Forall y k t
| otherwise -> A a $ Forall y k (subst x forY t)
Later t1 t2 -> A a (Later (subst x forY t1) (subst x forY t2))
RecTy t -> A a $ RecTy (subst x forY t)
TTuple ts -> A a $ TTuple (map (subst x forY) ts)
t1 `TApp` t2 -> A a $ subst x forY t1 `TApp` subst x forY t2
t1 :->: t2 -> A a $ subst x forY t1 :->: subst x forY t2
extractKappa :: Type a s -> Either String Name
extractKappa (A _ kv) =
case kv of
TExists k -> pure k
TVar k -> pure k
TFree k -> pure k
_ -> Left $ show $ "Expected clock variable but got" <+> pretty kv
|
f2d4816be620356a0217adcb53424eaa6fe57b36113591ee0ae99311dd73cbae | replikativ/datahike | integration_test.cljc | (ns ^:no-doc datahike.integration-test
"This namespace is the minimum test a Datahike backend needs to pass for compatibility assessment."
(:require [datahike.api :as d]
#?(:clj [clojure.test :refer :all]
:cljs [cljs.test :refer :all :include-macros true])))
(defn integration-test-fixture [config]
(d/delete-database config)
(d/create-database config)
(let [conn (d/connect config)]
(d/transact conn [{:db/ident :name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}
{:db/ident :age
:db/valueType :db.type/long
:db/cardinality :db.cardinality/one}])
;; lets add some data and wait for the transaction
(d/transact conn [{:name "Alice", :age 20}
{:name "Bob", :age 30}
{:name "Charlie", :age 40}
{:age 15}])
(d/release conn)))
(defn integration-test [config]
(let [conn (d/connect config)]
;; search the data
(is (= #{[3 "Alice" 20] [4 "Bob" 30] [5 "Charlie" 40]}
(d/q '[:find ?e ?n ?a
:where
[?e :name ?n]
[?e :age ?a]]
@conn)))
;; add new entity data using a hash map
(d/transact conn {:tx-data [{:db/id 3 :age 25}]})
;; if you want to work with queries like in
-query/ ,
;; you may use a hashmap
(is (= #{[5 "Charlie" 40] [4 "Bob" 30] [3 "Alice" 25]}
(d/q {:query '{:find [?e ?n ?a]
:where [[?e :name ?n]
[?e :age ?a]]}
:args [@conn]})))
;; query the history of the data
(is (= #{[20] [25]}
(d/q '[:find ?a
:where
[?e :name "Alice"]
[?e :age ?a]]
(d/history @conn))))
you might need to release the connection , e.g. for
(is (= nil (d/release conn)))
;; database should exist
(is (d/database-exists? config))
;; clean up the database if it is not needed any more
(d/delete-database config)
;; database should not exist
(is (not (d/database-exists? config)))))
| null | https://raw.githubusercontent.com/replikativ/datahike/7566d7c66b29f825e0f7b0dd6669f8faca6a0c39/src/datahike/integration_test.cljc | clojure | lets add some data and wait for the transaction
search the data
add new entity data using a hash map
if you want to work with queries like in
you may use a hashmap
query the history of the data
database should exist
clean up the database if it is not needed any more
database should not exist | (ns ^:no-doc datahike.integration-test
"This namespace is the minimum test a Datahike backend needs to pass for compatibility assessment."
(:require [datahike.api :as d]
#?(:clj [clojure.test :refer :all]
:cljs [cljs.test :refer :all :include-macros true])))
(defn integration-test-fixture [config]
(d/delete-database config)
(d/create-database config)
(let [conn (d/connect config)]
(d/transact conn [{:db/ident :name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}
{:db/ident :age
:db/valueType :db.type/long
:db/cardinality :db.cardinality/one}])
(d/transact conn [{:name "Alice", :age 20}
{:name "Bob", :age 30}
{:name "Charlie", :age 40}
{:age 15}])
(d/release conn)))
(defn integration-test [config]
(let [conn (d/connect config)]
(is (= #{[3 "Alice" 20] [4 "Bob" 30] [5 "Charlie" 40]}
(d/q '[:find ?e ?n ?a
:where
[?e :name ?n]
[?e :age ?a]]
@conn)))
(d/transact conn {:tx-data [{:db/id 3 :age 25}]})
-query/ ,
(is (= #{[5 "Charlie" 40] [4 "Bob" 30] [3 "Alice" 25]}
(d/q {:query '{:find [?e ?n ?a]
:where [[?e :name ?n]
[?e :age ?a]]}
:args [@conn]})))
(is (= #{[20] [25]}
(d/q '[:find ?a
:where
[?e :name "Alice"]
[?e :age ?a]]
(d/history @conn))))
you might need to release the connection , e.g. for
(is (= nil (d/release conn)))
(is (d/database-exists? config))
(d/delete-database config)
(is (not (d/database-exists? config)))))
|
0684e5a05f2ba26a0aad6ef81441a51f177267914ffca45510cf78adf83d9efc | rcook/aws-via-haskell | LambdaImports.hs | module LambdaImports
( _ResourceConflictException
, _ResourceNotFoundException
, FunctionCode
, Runtime(..)
, createFunction
, deleteFunction
, fcFunctionName
, fcZipFile
, functionCode
, invoke
, irsPayload
, lambda
, listFunctions
, lfrsFunctions
) where
import Network.AWS.Lambda
| null | https://raw.githubusercontent.com/rcook/aws-via-haskell/3ca6167307abb0628cfe4c9ca4545657b0f41494/lambda/LambdaImports.hs | haskell | module LambdaImports
( _ResourceConflictException
, _ResourceNotFoundException
, FunctionCode
, Runtime(..)
, createFunction
, deleteFunction
, fcFunctionName
, fcZipFile
, functionCode
, invoke
, irsPayload
, lambda
, listFunctions
, lfrsFunctions
) where
import Network.AWS.Lambda
| |
fd86363c847007497b099e404b4056e73d5aa41329e8b90a576aac5a3bbbebb3 | err0r500/realworld-app-simple-haskell | User.hs | module Adapter.Storage.InMem.User where
import qualified Data.Has as DH
import qualified Data.UUID as UUID
import qualified Domain.User as D
import RIO
import qualified RIO.Map as Map
import qualified Usecase.Interactor as UC
type InMemory r m = (DH.Has (TVar Store) r, MonadReader r m, MonadIO m)
data User = User
{ _id :: !UUID.UUID,
_name :: !Text,
_email :: !Text,
_password :: !Text
}
deriving (Show, Eq)
newtype Store = Store
{ users :: Map UUID.UUID User
}
fromDomain :: D.User -> User
( D._id d ) ( d ) ( D.unEmail $ D._email d ) " "
toDomain :: User -> D.User
toDomain u = D.User (_id u) (D.Name $ _name u) (D.Email $ _email u)
insertUserPswd :: InMemory r m => UC.InsertUserPswd m
insertUserPswd (D.User uid' (D.Name name') (D.Email email')) (D.Password password') = do
tvar <- asks DH.getter
atomically $ do
state <- readTVar tvar
writeTVar
tvar
state {users = Map.insert uid' (User uid' name' email' password') $ users state}
pure Nothing
getUserByID :: InMemory r m => UC.GetUserByID m
getUserByID userID = do
tvar <- asks DH.getter
atomically $ do
state <- readTVar tvar
pure $ Right $ toDomain <$> Map.lookup userID (users state)
getUserByEmail :: InMemory r m => UC.GetUserByEmail m
getUserByEmail (D.Email email') = commonSearch (\u -> email' == _email u)
getUserByName :: InMemory r m => UC.GetUserByName m
getUserByName (D.Name name') = commonSearch (\u -> name' == _name u)
getUserByEmailAndHashedPassword :: InMemory r m => UC.GetUserByEmailAndHashedPassword m
getUserByEmailAndHashedPassword (D.Email email') (D.Password pass') =
commonSearch (\u -> email' == _email u && pass' == _password u)
commonSearch :: InMemory r m => (User -> Bool) -> m (Either (UC.Err Void) (Maybe D.User))
commonSearch filter_ = do
tvar <- asks DH.getter
atomically $ do
state <- readTVar tvar
case filter filter_ $ map snd $ Map.toList (users state) of
[] -> pure $ Right Nothing
(x : _) -> pure $ Right (Just (toDomain x))
| null | https://raw.githubusercontent.com/err0r500/realworld-app-simple-haskell/20ec982256ec890f0c77b572eccef987cd3799bf/src/Adapter/Storage/InMem/User.hs | haskell | module Adapter.Storage.InMem.User where
import qualified Data.Has as DH
import qualified Data.UUID as UUID
import qualified Domain.User as D
import RIO
import qualified RIO.Map as Map
import qualified Usecase.Interactor as UC
type InMemory r m = (DH.Has (TVar Store) r, MonadReader r m, MonadIO m)
data User = User
{ _id :: !UUID.UUID,
_name :: !Text,
_email :: !Text,
_password :: !Text
}
deriving (Show, Eq)
newtype Store = Store
{ users :: Map UUID.UUID User
}
fromDomain :: D.User -> User
( D._id d ) ( d ) ( D.unEmail $ D._email d ) " "
toDomain :: User -> D.User
toDomain u = D.User (_id u) (D.Name $ _name u) (D.Email $ _email u)
insertUserPswd :: InMemory r m => UC.InsertUserPswd m
insertUserPswd (D.User uid' (D.Name name') (D.Email email')) (D.Password password') = do
tvar <- asks DH.getter
atomically $ do
state <- readTVar tvar
writeTVar
tvar
state {users = Map.insert uid' (User uid' name' email' password') $ users state}
pure Nothing
getUserByID :: InMemory r m => UC.GetUserByID m
getUserByID userID = do
tvar <- asks DH.getter
atomically $ do
state <- readTVar tvar
pure $ Right $ toDomain <$> Map.lookup userID (users state)
getUserByEmail :: InMemory r m => UC.GetUserByEmail m
getUserByEmail (D.Email email') = commonSearch (\u -> email' == _email u)
getUserByName :: InMemory r m => UC.GetUserByName m
getUserByName (D.Name name') = commonSearch (\u -> name' == _name u)
getUserByEmailAndHashedPassword :: InMemory r m => UC.GetUserByEmailAndHashedPassword m
getUserByEmailAndHashedPassword (D.Email email') (D.Password pass') =
commonSearch (\u -> email' == _email u && pass' == _password u)
commonSearch :: InMemory r m => (User -> Bool) -> m (Either (UC.Err Void) (Maybe D.User))
commonSearch filter_ = do
tvar <- asks DH.getter
atomically $ do
state <- readTVar tvar
case filter filter_ $ map snd $ Map.toList (users state) of
[] -> pure $ Right Nothing
(x : _) -> pure $ Right (Just (toDomain x))
| |
098c31babd615807386f5425906d82c4922127823ffca76bc60e189d1d855674 | spawngrid/htoad | blocktrans_extractor.erl | -module(blocktrans_extractor).
-export([extract/1]).
extract(Path) when is_list(Path) ->
{ok, Contents} = file:read_file(Path),
extract(Contents);
extract(Contents) when is_binary(Contents) ->
case erlydtl_compiler:parse(Contents) of
{ok, ParseTree} ->
Blocks = process_tree(ParseTree),
{ok, Blocks};
Error ->
Error
end.
process_tree(ParseTree) ->
process_tree(ParseTree, []).
process_tree([], Acc) ->
lists:reverse(Acc);
process_tree([{'autoescape', _, Contents}|Rest], Acc) ->
process_tree(Rest, lists:reverse(process_tree(Contents), Acc));
process_tree([{'block', _, Contents}|Rest], Acc) ->
process_tree(Rest, lists:reverse(process_tree(Contents), Acc));
process_tree([{'blocktrans', _, Contents}|Rest], Acc) ->
process_tree(Rest, [lists:flatten(erlydtl_unparser:unparse(Contents))|Acc]); % <-- where all the action happens
process_tree([{'filter', _, Contents}|Rest], Acc) ->
process_tree(Rest, lists:reverse(process_tree(Contents), Acc));
process_tree([{'for', _, Contents}|Rest], Acc) ->
process_tree(Rest, lists:reverse(process_tree(Contents), Acc));
process_tree([{'for', _, Contents, EmptyPartContents}|Rest], Acc) ->
process_tree(Rest, lists:reverse(process_tree(Contents) ++ process_tree(EmptyPartContents), Acc));
process_tree([{Instruction, _, Contents}|Rest], Acc) when Instruction =:= 'if';
Instruction =:= 'ifequal';
Instruction =:= 'ifnotequal' ->
process_tree(Rest, lists:reverse(process_tree(Contents), Acc));
process_tree([{Instruction, _, IfContents, ElseContents}|Rest], Acc) when Instruction =:= 'ifelese';
Instruction =:= 'ifequalelse';
Instruction =:= 'ifnotequalelse' ->
process_tree(Rest, lists:reverse(process_tree(IfContents) ++ process_tree(ElseContents), Acc));
process_tree([{'spaceless', Contents}|Rest], Acc) ->
process_tree(Rest, lists:reverse(process_tree(Contents), Acc));
process_tree([{'with', _, Contents}|Rest], Acc) ->
process_tree(Rest, lists:reverse(process_tree(Contents), Acc));
process_tree([_|Rest], Acc) ->
process_tree(Rest, Acc).
| null | https://raw.githubusercontent.com/spawngrid/htoad/f0c7dfbd911b29fb0c406b7c26606f553af11194/deps/erlydtl/src/i18n/blocktrans_extractor.erl | erlang | <-- where all the action happens | -module(blocktrans_extractor).
-export([extract/1]).
extract(Path) when is_list(Path) ->
{ok, Contents} = file:read_file(Path),
extract(Contents);
extract(Contents) when is_binary(Contents) ->
case erlydtl_compiler:parse(Contents) of
{ok, ParseTree} ->
Blocks = process_tree(ParseTree),
{ok, Blocks};
Error ->
Error
end.
process_tree(ParseTree) ->
process_tree(ParseTree, []).
process_tree([], Acc) ->
lists:reverse(Acc);
process_tree([{'autoescape', _, Contents}|Rest], Acc) ->
process_tree(Rest, lists:reverse(process_tree(Contents), Acc));
process_tree([{'block', _, Contents}|Rest], Acc) ->
process_tree(Rest, lists:reverse(process_tree(Contents), Acc));
process_tree([{'blocktrans', _, Contents}|Rest], Acc) ->
process_tree([{'filter', _, Contents}|Rest], Acc) ->
process_tree(Rest, lists:reverse(process_tree(Contents), Acc));
process_tree([{'for', _, Contents}|Rest], Acc) ->
process_tree(Rest, lists:reverse(process_tree(Contents), Acc));
process_tree([{'for', _, Contents, EmptyPartContents}|Rest], Acc) ->
process_tree(Rest, lists:reverse(process_tree(Contents) ++ process_tree(EmptyPartContents), Acc));
process_tree([{Instruction, _, Contents}|Rest], Acc) when Instruction =:= 'if';
Instruction =:= 'ifequal';
Instruction =:= 'ifnotequal' ->
process_tree(Rest, lists:reverse(process_tree(Contents), Acc));
process_tree([{Instruction, _, IfContents, ElseContents}|Rest], Acc) when Instruction =:= 'ifelese';
Instruction =:= 'ifequalelse';
Instruction =:= 'ifnotequalelse' ->
process_tree(Rest, lists:reverse(process_tree(IfContents) ++ process_tree(ElseContents), Acc));
process_tree([{'spaceless', Contents}|Rest], Acc) ->
process_tree(Rest, lists:reverse(process_tree(Contents), Acc));
process_tree([{'with', _, Contents}|Rest], Acc) ->
process_tree(Rest, lists:reverse(process_tree(Contents), Acc));
process_tree([_|Rest], Acc) ->
process_tree(Rest, Acc).
|
288580eec4691ba468c1246f5fbdb83c363ba7063b26a0a1922d2dd84c43ca57 | rafaeldelboni/graphmosphere | percent_encode.clj | (ns graphmosphere.percent-encode
(:require [clojure.string :as string]))
(set! *warn-on-reflection* true)
(def ^:private reserved-characters-regex #"[ !#$%&'()*+,/:;=?@\[\]]")
(defn ^:private char->percent-encode
"Percent-encoding a reserved character involves converting the character to its
corresponding byte value in ASCII and then representing that value as a pair of
hexadecimal digits. The digits, preceded by a percent sign (%) which is used as
an escape character, are then used in the URI in place of the reserved character."
[char]
(case char
" " "%20"
"!" "%21"
"#" "%23"
"$" "%24"
"%" "%25"
"&" "%26"
"'" "%27"
"(" "%28"
")" "%29"
"*" "%2A"
"+" "%2B"
"," "%2C"
"/" "%2F"
":" "%3A"
";" "%3B"
"=" "%3D"
"?" "%3F"
"@" "%40"
"[" "%5B"
"]" "%5D"
char))
(defn str->encode
"Percent-encoding, also known as URL encoding, is a method to encode arbitrary
data in a Uniform Resource Identifier (URI) using only the limited US-ASCII
characters legal within a URI."
[str]
(string/replace str reserved-characters-regex char->percent-encode))
| null | https://raw.githubusercontent.com/rafaeldelboni/graphmosphere/764904ee60674c5d5cbc83cb26d70c0bc5579385/src/graphmosphere/percent_encode.clj | clojure | (ns graphmosphere.percent-encode
(:require [clojure.string :as string]))
(set! *warn-on-reflection* true)
(def ^:private reserved-characters-regex #"[ !#$%&'()*+,/:;=?@\[\]]")
(defn ^:private char->percent-encode
"Percent-encoding a reserved character involves converting the character to its
corresponding byte value in ASCII and then representing that value as a pair of
hexadecimal digits. The digits, preceded by a percent sign (%) which is used as
an escape character, are then used in the URI in place of the reserved character."
[char]
(case char
" " "%20"
"!" "%21"
"#" "%23"
"$" "%24"
"%" "%25"
"&" "%26"
"'" "%27"
"(" "%28"
")" "%29"
"*" "%2A"
"+" "%2B"
"," "%2C"
"/" "%2F"
":" "%3A"
";" "%3B"
"=" "%3D"
"?" "%3F"
"@" "%40"
"[" "%5B"
"]" "%5D"
char))
(defn str->encode
"Percent-encoding, also known as URL encoding, is a method to encode arbitrary
data in a Uniform Resource Identifier (URI) using only the limited US-ASCII
characters legal within a URI."
[str]
(string/replace str reserved-characters-regex char->percent-encode))
| |
36f87870ca9a5135e2b9b23dfee060b92d015a7807b8dec9fdbfb668a3fb4282 | jordanthayer/ocaml-search | tpl_aseps_algs.ml | open Tpl_search_reg
(******** A*-epsilon ****)
let aseps wt d p l =
let root, expand, goal_p, hd_close = Tpl_regression.init_aseps d p in
Aseps.a_star_eps ~limit:l root goal_p expand hd_close wt
let aseps_old wt d p l =
let root, expand, goal_p, hd_close = Tpl_regression.init_aseps d p in
Aseps.a_star_eps_old ~limit:l root goal_p expand hd_close wt
* f , then f^
let f_then_global wt d p l =
let root, expand, goal_p, hd = Tpl_regression.init_aseps d p in
F_fhat.george_global_err ~limit:l root goal_p expand hd wt
let f_then_level wt d p l =
let root, expand, goal_p, hd = Tpl_regression.init_aseps d p in
F_fhat.george_level_err ~limit:l root goal_p expand hd wt
let f_then_level_smooth wt d p l =
let root, expand, goal_p, hd = Tpl_regression.init_aseps d p in
F_fhat.george_level_smooth_err ~limit:l root goal_p expand hd wt
let f_then_path wt d p l =
let root, expand, goal_p, hd = Tpl_regression.init_aseps d p in
F_fhat.george_path_err ~limit:l root goal_p expand hd wt
let f_then_window wt d p l =
let root, expand, goal_p, hd = Tpl_regression.init_aseps d p in
F_fhat.george_window_err ~limit:l root goal_p expand hd wt
let f_then_classic_w wt d p l =
let root, expand, goal_p, hd = Tpl_regression.init_aseps d p in
F_fhat.george_classic_w ~limit:l root goal_p expand hd wt
let aseps_george_clean weight d p l =
let root, expand, goal_p, hd = Tpl_regression.init_aseps d p in
F_fhat.george_global_err_cleanup ~limit:l
root
goal_p
expand
hd
weight
let fhat_eps weight d p l =
let root, expand, goal_p, hd = Tpl_regression.init_aseps d p in
F_fhat.george_lms_cleanup ~limit:l
root
goal_p
expand
hd
weight
let strip_dups (sfop, a, b, c, d, e) =
sfop,a,b,c,d
let tqs weight d p l =
let root, expand, goal_p, hd = Tpl_regression.init_aseps d p in
Tqs_nodups.tqs ~limit:l
root
goal_p
expand
hd
weight
let aseps_george_clean2 weight d p l =
strip_dups
(let root, expand, goal_p, hd = Tpl_regression.init_aseps d p in
F_fhat.george_global_err_dups_cleanup ~limit:l
root
goal_p
expand
Tpl_regression.key
hd
weight)
(** f^ then f *)
| null | https://raw.githubusercontent.com/jordanthayer/ocaml-search/57cfc85417aa97ee5d8fbcdb84c333aae148175f/tplan/tpl_aseps_algs.ml | ocaml | ******* A*-epsilon ***
* f^ then f | open Tpl_search_reg
let aseps wt d p l =
let root, expand, goal_p, hd_close = Tpl_regression.init_aseps d p in
Aseps.a_star_eps ~limit:l root goal_p expand hd_close wt
let aseps_old wt d p l =
let root, expand, goal_p, hd_close = Tpl_regression.init_aseps d p in
Aseps.a_star_eps_old ~limit:l root goal_p expand hd_close wt
* f , then f^
let f_then_global wt d p l =
let root, expand, goal_p, hd = Tpl_regression.init_aseps d p in
F_fhat.george_global_err ~limit:l root goal_p expand hd wt
let f_then_level wt d p l =
let root, expand, goal_p, hd = Tpl_regression.init_aseps d p in
F_fhat.george_level_err ~limit:l root goal_p expand hd wt
let f_then_level_smooth wt d p l =
let root, expand, goal_p, hd = Tpl_regression.init_aseps d p in
F_fhat.george_level_smooth_err ~limit:l root goal_p expand hd wt
let f_then_path wt d p l =
let root, expand, goal_p, hd = Tpl_regression.init_aseps d p in
F_fhat.george_path_err ~limit:l root goal_p expand hd wt
let f_then_window wt d p l =
let root, expand, goal_p, hd = Tpl_regression.init_aseps d p in
F_fhat.george_window_err ~limit:l root goal_p expand hd wt
let f_then_classic_w wt d p l =
let root, expand, goal_p, hd = Tpl_regression.init_aseps d p in
F_fhat.george_classic_w ~limit:l root goal_p expand hd wt
let aseps_george_clean weight d p l =
let root, expand, goal_p, hd = Tpl_regression.init_aseps d p in
F_fhat.george_global_err_cleanup ~limit:l
root
goal_p
expand
hd
weight
let fhat_eps weight d p l =
let root, expand, goal_p, hd = Tpl_regression.init_aseps d p in
F_fhat.george_lms_cleanup ~limit:l
root
goal_p
expand
hd
weight
let strip_dups (sfop, a, b, c, d, e) =
sfop,a,b,c,d
let tqs weight d p l =
let root, expand, goal_p, hd = Tpl_regression.init_aseps d p in
Tqs_nodups.tqs ~limit:l
root
goal_p
expand
hd
weight
let aseps_george_clean2 weight d p l =
strip_dups
(let root, expand, goal_p, hd = Tpl_regression.init_aseps d p in
F_fhat.george_global_err_dups_cleanup ~limit:l
root
goal_p
expand
Tpl_regression.key
hd
weight)
|
b2a6c8bf8f70e62b146504ba64e05d94c1211ce231ce3561fa4ad73e7b939c0b | amnh/PCG | TRead.hs | ----------------------------------------------------------------------------
-- |
Module : File . Format . TNT.Command .
Copyright : ( c ) 2015 - 2021 Ward Wheeler
-- License : BSD-style
--
-- Maintainer :
-- Stability : provisional
-- Portability : portable
--
Parser for the TREAD command specifying how to read a forests of trees .
-- No validation currently takes place.
-----------------------------------------------------------------------------
# LANGUAGE FlexibleContexts #
# LANGUAGE TypeFamilies #
module File.Format.TNT.Command.TRead
( treadCommand
, treadHeader
, treadLeaf
, treadTree
) where
import Data.CaseInsensitive (FoldCase)
import Data.Char (isSpace)
import Data.Functor (($>))
import Data.List (isSuffixOf)
import qualified Data.List.NonEmpty as NE (fromList)
import File.Format.TNT.Internal
import Text.Megaparsec
import Text.Megaparsec.Char
import Text.Megaparsec.Custom
-- |
-- Parses an TREAD command. Correctly validates for taxa count
and character sequence length . Produces one or more taxa sequences .
treadCommand :: (FoldCase (Tokens s), MonadFail m, MonadParsec e s m, Token s ~ Char) => m TRead
treadCommand = treadValidation =<< treadDefinition
where
treadDefinition = symbol treadHeader
*> symbol treadForest
<* symbol (char ';')
treadValidation = pure -- No validation yet (what to validate?)
-- |
The superfluous information of an XREAD command . Consumes the XREAD string
identifier and zero or more comments preceding the taxa count and character
-- count parameters
treadHeader :: (FoldCase (Tokens s), MonadFail m, MonadParsec e s m, Token s ~ Char) => m ()
treadHeader = symbol (keyword "tread" 2)
*> many simpleComment
$> ()
where
simpleComment = delimiter *> anythingTill delimiter <* symbol delimiter
where
delimiter = char '\''
-- |
One or more ' * ' separated trees in parenthetical notationy
treadForest :: (MonadFail m, MonadParsec e s m, Token s ~ Char) => m TRead
treadForest = fmap NE.fromList $ symbol treadTree `sepBy1` symbol (char '*')
-- |
-- A bifurcating, rooted tree with data only on the leaf nodes.
treadTree :: (MonadFail m, MonadParsec e s m, Token s ~ Char) => m TReadTree
treadTree = treadSubtree <|> treadLeaf
-- |
A leaf node of the TREAD tree , representing one of the three possible
-- identifier types used for matching with a taxon from the taxa set.
treadLeaf :: (MonadFail m, MonadParsec e s m, Token s ~ Char) => m TReadTree
treadLeaf = Leaf <$> choice [try index, try prefix, name]
where
index = Index <$> flexibleNonNegativeInt "taxon reference index"
prefix = Prefix <$> (taxaLabel >>= checkTail)
name = Name <$> taxaLabel
taxaLabel = some labelChar
labelChar = satisfy (\x -> not (isSpace x) && x `notElem` "(),;")
checkTail x = if "..." `isSuffixOf` x then pure x else fail "oops"
-- |
-- A branch of the TREAD tree. each branch can be either a leaf or a sub tree.
treadSubtree :: (MonadFail m, MonadParsec e s m, Token s ~ Char) => m TReadTree
treadSubtree = between open close body
where
open = symbol (char '(')
close = symbol (char ')')
body = Branch <$> some (symbol treadTree)
| null | https://raw.githubusercontent.com/amnh/PCG/9341efe0ec2053302c22b4466157d0a24ed18154/lib/file-parsers/src/File/Format/TNT/Command/TRead.hs | haskell | --------------------------------------------------------------------------
|
License : BSD-style
Maintainer :
Stability : provisional
Portability : portable
No validation currently takes place.
---------------------------------------------------------------------------
|
Parses an TREAD command. Correctly validates for taxa count
No validation yet (what to validate?)
|
count parameters
|
|
A bifurcating, rooted tree with data only on the leaf nodes.
|
identifier types used for matching with a taxon from the taxa set.
|
A branch of the TREAD tree. each branch can be either a leaf or a sub tree. | Module : File . Format . TNT.Command .
Copyright : ( c ) 2015 - 2021 Ward Wheeler
Parser for the TREAD command specifying how to read a forests of trees .
# LANGUAGE FlexibleContexts #
# LANGUAGE TypeFamilies #
module File.Format.TNT.Command.TRead
( treadCommand
, treadHeader
, treadLeaf
, treadTree
) where
import Data.CaseInsensitive (FoldCase)
import Data.Char (isSpace)
import Data.Functor (($>))
import Data.List (isSuffixOf)
import qualified Data.List.NonEmpty as NE (fromList)
import File.Format.TNT.Internal
import Text.Megaparsec
import Text.Megaparsec.Char
import Text.Megaparsec.Custom
and character sequence length . Produces one or more taxa sequences .
treadCommand :: (FoldCase (Tokens s), MonadFail m, MonadParsec e s m, Token s ~ Char) => m TRead
treadCommand = treadValidation =<< treadDefinition
where
treadDefinition = symbol treadHeader
*> symbol treadForest
<* symbol (char ';')
The superfluous information of an XREAD command . Consumes the XREAD string
identifier and zero or more comments preceding the taxa count and character
treadHeader :: (FoldCase (Tokens s), MonadFail m, MonadParsec e s m, Token s ~ Char) => m ()
treadHeader = symbol (keyword "tread" 2)
*> many simpleComment
$> ()
where
simpleComment = delimiter *> anythingTill delimiter <* symbol delimiter
where
delimiter = char '\''
One or more ' * ' separated trees in parenthetical notationy
treadForest :: (MonadFail m, MonadParsec e s m, Token s ~ Char) => m TRead
treadForest = fmap NE.fromList $ symbol treadTree `sepBy1` symbol (char '*')
treadTree :: (MonadFail m, MonadParsec e s m, Token s ~ Char) => m TReadTree
treadTree = treadSubtree <|> treadLeaf
A leaf node of the TREAD tree , representing one of the three possible
treadLeaf :: (MonadFail m, MonadParsec e s m, Token s ~ Char) => m TReadTree
treadLeaf = Leaf <$> choice [try index, try prefix, name]
where
index = Index <$> flexibleNonNegativeInt "taxon reference index"
prefix = Prefix <$> (taxaLabel >>= checkTail)
name = Name <$> taxaLabel
taxaLabel = some labelChar
labelChar = satisfy (\x -> not (isSpace x) && x `notElem` "(),;")
checkTail x = if "..." `isSuffixOf` x then pure x else fail "oops"
treadSubtree :: (MonadFail m, MonadParsec e s m, Token s ~ Char) => m TReadTree
treadSubtree = between open close body
where
open = symbol (char '(')
close = symbol (char ')')
body = Branch <$> some (symbol treadTree)
|
44947fe5ac8d74be3765b3aa337f23bccab55e305d5f285044acb68eb18a0995 | joelmccracken/reddup | Trackable.hs | {-# LANGUAGE OverloadedStrings #-}
module Trackable where
import Prelude hiding (FilePath, concat)
import qualified Turtle as Tu
import qualified ShellUtil
import qualified Config as C
import qualified Handler as H
import qualified Handler.Git as HG
import qualified Reddup as R
import Trackable.Data
import Trackable.Util
import Control.Monad.Reader
handleTrackable :: Trackable -> R.Reddup ()
handleTrackable trackable = do
case trackable of
(GitRepo grTrack) ->
HG.gitHandler' grTrack
(InboxDir idTrack) ->
processInboxTrackable idTrack >>= H.handleInbox
processInboxTrackable :: InboxDirTrackable -> R.Reddup NHFile
processInboxTrackable idt@(InboxDirTrackable dir _locSpec)= do
dir' <- lift $ pathToTextOrError dir
R.verbose $ "checking " <> dir'
lift $ Tu.cd dir
let files = lift $ Tu.ls dir
files >>= (lift . return . NHFile idt)
configToTrackables :: R.Reddup Trackable
configToTrackables = do
reddup <- ask
location <- lift $ Tu.select $ C.locations $ C.rawConfig $ R.reddupConfig reddup
lift $ locationSpecToTrackable location
locationSpecToTrackable :: C.LocationSpec -> Tu.Shell Trackable
locationSpecToTrackable ls = do
let expand location =
(Tu.fromText . Tu.lineToText) <$> (ShellUtil.expandGlob location)
case ls of
C.GitLoc (C.GitLocation location _) -> do
path' <- (expand location)
return $ GitRepo $ GitRepoTrackable path' ls
C.InboxLoc (C.InboxLocation location _) -> do
path' <- (expand location)
return $ InboxDir $ InboxDirTrackable path' ls
| null | https://raw.githubusercontent.com/joelmccracken/reddup/1bce9371d79c410b30b91c10bf040777260777ad/src/Trackable.hs | haskell | # LANGUAGE OverloadedStrings # |
module Trackable where
import Prelude hiding (FilePath, concat)
import qualified Turtle as Tu
import qualified ShellUtil
import qualified Config as C
import qualified Handler as H
import qualified Handler.Git as HG
import qualified Reddup as R
import Trackable.Data
import Trackable.Util
import Control.Monad.Reader
handleTrackable :: Trackable -> R.Reddup ()
handleTrackable trackable = do
case trackable of
(GitRepo grTrack) ->
HG.gitHandler' grTrack
(InboxDir idTrack) ->
processInboxTrackable idTrack >>= H.handleInbox
processInboxTrackable :: InboxDirTrackable -> R.Reddup NHFile
processInboxTrackable idt@(InboxDirTrackable dir _locSpec)= do
dir' <- lift $ pathToTextOrError dir
R.verbose $ "checking " <> dir'
lift $ Tu.cd dir
let files = lift $ Tu.ls dir
files >>= (lift . return . NHFile idt)
configToTrackables :: R.Reddup Trackable
configToTrackables = do
reddup <- ask
location <- lift $ Tu.select $ C.locations $ C.rawConfig $ R.reddupConfig reddup
lift $ locationSpecToTrackable location
locationSpecToTrackable :: C.LocationSpec -> Tu.Shell Trackable
locationSpecToTrackable ls = do
let expand location =
(Tu.fromText . Tu.lineToText) <$> (ShellUtil.expandGlob location)
case ls of
C.GitLoc (C.GitLocation location _) -> do
path' <- (expand location)
return $ GitRepo $ GitRepoTrackable path' ls
C.InboxLoc (C.InboxLocation location _) -> do
path' <- (expand location)
return $ InboxDir $ InboxDirTrackable path' ls
|
d79de3450efe58b6ee2c7bb231ef0996a1bbdc84d47b7d82a6e8dd22d4a05388 | elizabethsiegle/reddit-slack-bot | APIKey.hs | # LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
{-#LANGUAGE OverloadedStrings #-}
# LANGUAGE ViewPatterns #
module Twilio.APIKey
( -- * Resource
APIKey(..)
, APIKeySID
, Twilio.APIKey.get
) where
import Control.Applicative
import Control.Monad
import Control.Monad.Catch
import Data.Aeson
import Data.Monoid
import Data.Text (Text)
import Data.Time.Clock
import Network.URI
import Control.Monad.Twilio
import Twilio.Internal.Parser
import Twilio.Internal.Request
import Twilio.Internal.Resource as Resource
import Twilio.Types
Resource
data APIKey = APIKey
{ sid :: !APIKeySID
, friendlyName :: !Text
, secret :: !(Maybe Text)
, dateCreated :: !UTCTime
, dateUpdated :: !UTCTime
} deriving (Show, Eq, Ord)
instance FromJSON APIKey where
parseJSON (Object v) = APIKey
<$> v .: "sid"
<*> v .: "friendly_name"
<*> v .:? "secret"
<*> (v .: "date_created" >>= parseDateTime)
<*> (v .: "date_updated" >>= parseDateTime)
parseJSON _ = mzero
instance Get1 APIKeySID APIKey where
get1 (getSID -> sid) = request parseJSONFromResponse =<< makeTwilioRequest
("/Keys/" <> sid <> ".json")
get :: MonadThrow m => APIKeySID -> TwilioT m APIKey
get = Resource.get
| null | https://raw.githubusercontent.com/elizabethsiegle/reddit-slack-bot/a52ab60dcaae8e16bee8cdba22fce627157a42d8/twilio-haskell-move-to-stack/src/Twilio/APIKey.hs | haskell | #LANGUAGE OverloadedStrings #
* Resource | # LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE ViewPatterns #
module Twilio.APIKey
APIKey(..)
, APIKeySID
, Twilio.APIKey.get
) where
import Control.Applicative
import Control.Monad
import Control.Monad.Catch
import Data.Aeson
import Data.Monoid
import Data.Text (Text)
import Data.Time.Clock
import Network.URI
import Control.Monad.Twilio
import Twilio.Internal.Parser
import Twilio.Internal.Request
import Twilio.Internal.Resource as Resource
import Twilio.Types
Resource
data APIKey = APIKey
{ sid :: !APIKeySID
, friendlyName :: !Text
, secret :: !(Maybe Text)
, dateCreated :: !UTCTime
, dateUpdated :: !UTCTime
} deriving (Show, Eq, Ord)
instance FromJSON APIKey where
parseJSON (Object v) = APIKey
<$> v .: "sid"
<*> v .: "friendly_name"
<*> v .:? "secret"
<*> (v .: "date_created" >>= parseDateTime)
<*> (v .: "date_updated" >>= parseDateTime)
parseJSON _ = mzero
instance Get1 APIKeySID APIKey where
get1 (getSID -> sid) = request parseJSONFromResponse =<< makeTwilioRequest
("/Keys/" <> sid <> ".json")
get :: MonadThrow m => APIKeySID -> TwilioT m APIKey
get = Resource.get
|
571ae6f1b22f7727acde058a77ceccf5ffa600bfd75d29a393b84f52ba6be7c9 | CIFASIS/QuickFuzz | Regex.hs | # LANGUAGE FlexibleInstances #
# LANGUAGE IncoherentInstances #
# LANGUAGE TemplateHaskell #
module Test.QuickFuzz.Gen.Base.Regex where
import Control.DeepSeq
import Data.Default
import Data.Char (chr)
import Data.List (intersperse, partition, subsequences)
import Data.Set (Set)
import qualified Data.Set as Set (toAscList, toList)
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy.Char8 as LC8
import Test.QuickCheck hiding (shrink)
import Test.QuickFuzz.Derive
import Test.QuickFuzz.Derive.Generator
import Test.QuickFuzz.Derive.NFData
import Test.QuickFuzz.Gen.Base.ByteString
import Test.QuickFuzz.Gen.FormatInfo
data Pattern = PEmpty | PCarat | PDollar
| PGroup PatternIndex Pattern
-- | PGroup' PatternIndex (Maybe PatternIndex) Pattern -- used in longest match
| POr [Pattern]
| PConcat [Pattern]
| PQuest Pattern
| PPlus Pattern
| PStar Pattern
| PBound Int (Maybe Int) Pattern
| PLazy indicates the pattern should find the shortest match first
| PLazy Pattern -- non-greedy wrapper (for ?+*{} followed by ?)
-- | PPossessive indicates the pattern can only find the longest match
| PPossessive Pattern -- possessive modifier (for ?+*{} followed by +)
| PDot -- Any character (newline?) at all
| PAny PatternSet -- Square bracketed things
| PAnyNot PatternSet -- Inverted square bracketed things
| PEscape Char -- Backslashed Character
| PBack PatternIndex -- Backslashed digits as natural number
| PChar Char -- Specific Character
After simplify / mergeCharToString , adjacent PChar are merge'd into PString
| PString String
deriving (Eq,Show)
showPattern :: Pattern -> String
showPattern pIn =
case pIn of
PEmpty -> "()"
PCarat -> "^"
PDollar -> "$"
PGroup _ p -> ('(':showPattern p)++")"
POr ps -> concat $ intersperse "|" (map showPattern ps)
PConcat ps -> concatMap showPattern ps
PQuest p -> (showPattern p)++"?"
PPlus p -> (showPattern p)++"+"
PStar p -> (showPattern p)++"*"
PLazy p -> (showPattern p)++"?"
| otherwise - > " < Can not print PLazy of " + + show p++ " > "
PPossessive p -> (showPattern p)++"+"
| otherwise - > " < Can not print PPossessive of " + + show p++ " > "
PBound i (Just j) p | i==j -> showPattern p ++ ('{':show i)++"}"
PBound i mj p -> showPattern p ++ ('{':show i) ++ maybe ",}" (\j -> ',':show j++"}") mj
PDot -> "."
PAny (PatternSet s scc sce sec) ->
let (special,normal) = maybe ("","") ((partition (`elem` "]-")) . Set.toAscList) s
charSpec = (if ']' `elem` special then (']':) else id) (byRange normal)
scc' = maybe "" ((concatMap (\ss -> "[:"++unSCC ss++":]")) . Set.toList) scc
sce' = maybe "" ((concatMap (\ss -> "[."++unSCE ss++".]")) . Set.toList) sce
sec' = maybe "" ((concatMap (\ss -> "[="++unSEC ss++"=]")) . Set.toList) sec
in concat ['[':charSpec,scc',sce',sec',if '-' `elem` special then "-]" else "]"]
PAnyNot (PatternSet s scc sce sec) ->
let (special,normal) = maybe ("","") ((partition (`elem` "]-")) . Set.toAscList) s
charSpec = (if ']' `elem` special then (']':) else id) (byRange normal)
scc' = maybe "" ((concatMap (\ss -> "[:"++unSCC ss++":]")) . Set.toList) scc
sce' = maybe "" ((concatMap (\ss -> "[."++unSCE ss++".]")) . Set.toList) sce
sec' = maybe "" ((concatMap (\ss -> "[="++unSEC ss++"=]")) . Set.toList) sec
in concat ["[^",charSpec,scc',sce',sec',if '-' `elem` special then "-]" else "]"]
PEscape c -> '\\':c:[]
PBack i -> '\\':(show i)
PChar c -> [c]
PString s -> s
where byRange xAll@(x:xs) | length xAll <=3 = xAll
| otherwise = groupRange x 1 xs
byRange _ = ""
groupRange x n (y:ys) = if (fromEnum y)-(fromEnum x) == n then groupRange x (succ n) ys
else (if n <=3 then take n [x..]
else x:'-':(toEnum (pred n+fromEnum x)):[]) ++ groupRange y 1 ys
groupRange x n [] = if n <=3 then take n [x..]
else x:'-':(toEnum (pred n+fromEnum x)):[]
data PatternSet = PatternSet (Maybe (Set Char)) (Maybe (Set (PatternSetCharacterClass)))
(Maybe (Set PatternSetCollatingElement)) (Maybe (Set PatternSetEquivalenceClass)) deriving (Eq,Show)
newtype PatternSetCharacterClass = PatternSetCharacterClass {unSCC::String} deriving (Eq,Ord,Show) -- [: :]
newtype PatternSetCollatingElement = PatternSetCollatingElement {unSCE::String} deriving (Eq,Ord,Show) -- [. .]
newtype PatternSetEquivalenceClass = PatternSetEquivalenceClass {unSEC::String} deriving (Eq,Ord,Show) -- [= =]
| PatternIndex is for indexing submatches from parenthesized groups ( PGroup )
type PatternIndex = Int
-- helper function
isPostAtom :: Pattern -> Bool
isPostAtom p = case p of
PQuest _ -> True
PPlus _ -> True
PStar _ -> True
PBound _ _ _ -> True
_ -> False
$(devArbitrary ''Pattern)
$(devNFData ''Pattern)
$(devGenerator "genPattern" ''Pattern)
type Regex = Pattern
shrinkRegex :: Regex -> [Regex]
shrinkRegex PEmpty = []
shrinkRegex PCarat = []
shrinkRegex PDollar = []
shrinkRegex PDot = []
shrinkRegex x = [PEmpty, PCarat, PDollar, PDot] ++ shrinkRegex' x
shrinkRegex' PEmpty = [PEmpty]
shrinkRegex' PCarat = [PCarat]
shrinkRegex' PDollar = [PDollar]
shrinkRegex' PDot = [PDot]
shrinkRegex' (PGroup i p) = [p] ++ [PGroup i' p' | i' <- shrinkInt i, p' <- shrinkRegex' p]
shrinkRegex' (POr ps) = [POr ps'' | ps'' <- subsequences ps, ps' <- shrinkListOfPattern ps]
shrinkRegex' (PConcat ps) = [POr ps' | ps' <- shrinkListOfPattern ps]
shrinkRegex' (PQuest p) = [p] ++ [PQuest p' | p' <- shrinkRegex' p]
shrinkRegex' (PPlus p) = [p] ++ [PPlus p' | p' <- shrinkRegex' p]
shrinkRegex' (PStar p) = [p] ++[PStar p' | p' <- shrinkRegex' p]
shrinkRegex' (PBound i mi p) = [p] ++ [PBound i' mi' p'| i' <- shrinkInt i, mi' <- shrinkMaybe mi, p' <- shrinkRegex' p]
shrinkRegex' (PLazy p) = [p] ++[PLazy p' | p' <- shrinkRegex' p]
shrinkRegex' (PPossessive p) = [p] ++ [PPossessive p' | p' <- shrinkRegex' p]
shrinkRegex' (PAny pset) = [PAny pset' | pset' <- shrinkPatternSet pset]
shrinkRegex' (PAnyNot pset) = [PAnyNot pset' | pset' <- shrinkPatternSet pset]
shrinkRegex' (PEscape c) = [PEscape c' | c' <- shrinkChar c]
shrinkRegex' (PBack pi) = [PBack pi' | pi' <- shrinkPatternIndex pi]
shrinkRegex' (PChar c) = [PChar c' | c' <- shrinkChar c]
shrinkRegex' (PString str) = [PString str' | str' <- shrinkString str]
shrinkInt x = [x]
shrinkMaybe x = [x]
shrinkPatternSet x = [x]
shrinkPatternIndex x = [x]
shrinkChar c = [c]
shrinkString = subsequences
shrinkListOfPattern xs = map shrinkRegex' xs
mencode :: Regex -> LC8.ByteString
mencode x = LC8.pack $ "/" ++ showPattern x ++ "/"
regexInfo :: FormatInfo Regex NoActions
regexInfo = def
{ encode = mencode
, random = arbitrary
, value = show
, shrink = shrinkRegex
, ext = "regex"
}
| null | https://raw.githubusercontent.com/CIFASIS/QuickFuzz/a1c69f028b0960c002cb83e8145f039ecc0e0a23/src/Test/QuickFuzz/Gen/Base/Regex.hs | haskell | | PGroup' PatternIndex (Maybe PatternIndex) Pattern -- used in longest match
non-greedy wrapper (for ?+*{} followed by ?)
| PPossessive indicates the pattern can only find the longest match
possessive modifier (for ?+*{} followed by +)
Any character (newline?) at all
Square bracketed things
Inverted square bracketed things
Backslashed Character
Backslashed digits as natural number
Specific Character
[: :]
[. .]
[= =]
helper function | # LANGUAGE FlexibleInstances #
# LANGUAGE IncoherentInstances #
# LANGUAGE TemplateHaskell #
module Test.QuickFuzz.Gen.Base.Regex where
import Control.DeepSeq
import Data.Default
import Data.Char (chr)
import Data.List (intersperse, partition, subsequences)
import Data.Set (Set)
import qualified Data.Set as Set (toAscList, toList)
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy.Char8 as LC8
import Test.QuickCheck hiding (shrink)
import Test.QuickFuzz.Derive
import Test.QuickFuzz.Derive.Generator
import Test.QuickFuzz.Derive.NFData
import Test.QuickFuzz.Gen.Base.ByteString
import Test.QuickFuzz.Gen.FormatInfo
data Pattern = PEmpty | PCarat | PDollar
| PGroup PatternIndex Pattern
| POr [Pattern]
| PConcat [Pattern]
| PQuest Pattern
| PPlus Pattern
| PStar Pattern
| PBound Int (Maybe Int) Pattern
| PLazy indicates the pattern should find the shortest match first
After simplify / mergeCharToString , adjacent PChar are merge'd into PString
| PString String
deriving (Eq,Show)
showPattern :: Pattern -> String
showPattern pIn =
case pIn of
PEmpty -> "()"
PCarat -> "^"
PDollar -> "$"
PGroup _ p -> ('(':showPattern p)++")"
POr ps -> concat $ intersperse "|" (map showPattern ps)
PConcat ps -> concatMap showPattern ps
PQuest p -> (showPattern p)++"?"
PPlus p -> (showPattern p)++"+"
PStar p -> (showPattern p)++"*"
PLazy p -> (showPattern p)++"?"
| otherwise - > " < Can not print PLazy of " + + show p++ " > "
PPossessive p -> (showPattern p)++"+"
| otherwise - > " < Can not print PPossessive of " + + show p++ " > "
PBound i (Just j) p | i==j -> showPattern p ++ ('{':show i)++"}"
PBound i mj p -> showPattern p ++ ('{':show i) ++ maybe ",}" (\j -> ',':show j++"}") mj
PDot -> "."
PAny (PatternSet s scc sce sec) ->
let (special,normal) = maybe ("","") ((partition (`elem` "]-")) . Set.toAscList) s
charSpec = (if ']' `elem` special then (']':) else id) (byRange normal)
scc' = maybe "" ((concatMap (\ss -> "[:"++unSCC ss++":]")) . Set.toList) scc
sce' = maybe "" ((concatMap (\ss -> "[."++unSCE ss++".]")) . Set.toList) sce
sec' = maybe "" ((concatMap (\ss -> "[="++unSEC ss++"=]")) . Set.toList) sec
in concat ['[':charSpec,scc',sce',sec',if '-' `elem` special then "-]" else "]"]
PAnyNot (PatternSet s scc sce sec) ->
let (special,normal) = maybe ("","") ((partition (`elem` "]-")) . Set.toAscList) s
charSpec = (if ']' `elem` special then (']':) else id) (byRange normal)
scc' = maybe "" ((concatMap (\ss -> "[:"++unSCC ss++":]")) . Set.toList) scc
sce' = maybe "" ((concatMap (\ss -> "[."++unSCE ss++".]")) . Set.toList) sce
sec' = maybe "" ((concatMap (\ss -> "[="++unSEC ss++"=]")) . Set.toList) sec
in concat ["[^",charSpec,scc',sce',sec',if '-' `elem` special then "-]" else "]"]
PEscape c -> '\\':c:[]
PBack i -> '\\':(show i)
PChar c -> [c]
PString s -> s
where byRange xAll@(x:xs) | length xAll <=3 = xAll
| otherwise = groupRange x 1 xs
byRange _ = ""
groupRange x n (y:ys) = if (fromEnum y)-(fromEnum x) == n then groupRange x (succ n) ys
else (if n <=3 then take n [x..]
else x:'-':(toEnum (pred n+fromEnum x)):[]) ++ groupRange y 1 ys
groupRange x n [] = if n <=3 then take n [x..]
else x:'-':(toEnum (pred n+fromEnum x)):[]
data PatternSet = PatternSet (Maybe (Set Char)) (Maybe (Set (PatternSetCharacterClass)))
(Maybe (Set PatternSetCollatingElement)) (Maybe (Set PatternSetEquivalenceClass)) deriving (Eq,Show)
| PatternIndex is for indexing submatches from parenthesized groups ( PGroup )
type PatternIndex = Int
isPostAtom :: Pattern -> Bool
isPostAtom p = case p of
PQuest _ -> True
PPlus _ -> True
PStar _ -> True
PBound _ _ _ -> True
_ -> False
$(devArbitrary ''Pattern)
$(devNFData ''Pattern)
$(devGenerator "genPattern" ''Pattern)
type Regex = Pattern
shrinkRegex :: Regex -> [Regex]
shrinkRegex PEmpty = []
shrinkRegex PCarat = []
shrinkRegex PDollar = []
shrinkRegex PDot = []
shrinkRegex x = [PEmpty, PCarat, PDollar, PDot] ++ shrinkRegex' x
shrinkRegex' PEmpty = [PEmpty]
shrinkRegex' PCarat = [PCarat]
shrinkRegex' PDollar = [PDollar]
shrinkRegex' PDot = [PDot]
shrinkRegex' (PGroup i p) = [p] ++ [PGroup i' p' | i' <- shrinkInt i, p' <- shrinkRegex' p]
shrinkRegex' (POr ps) = [POr ps'' | ps'' <- subsequences ps, ps' <- shrinkListOfPattern ps]
shrinkRegex' (PConcat ps) = [POr ps' | ps' <- shrinkListOfPattern ps]
shrinkRegex' (PQuest p) = [p] ++ [PQuest p' | p' <- shrinkRegex' p]
shrinkRegex' (PPlus p) = [p] ++ [PPlus p' | p' <- shrinkRegex' p]
shrinkRegex' (PStar p) = [p] ++[PStar p' | p' <- shrinkRegex' p]
shrinkRegex' (PBound i mi p) = [p] ++ [PBound i' mi' p'| i' <- shrinkInt i, mi' <- shrinkMaybe mi, p' <- shrinkRegex' p]
shrinkRegex' (PLazy p) = [p] ++[PLazy p' | p' <- shrinkRegex' p]
shrinkRegex' (PPossessive p) = [p] ++ [PPossessive p' | p' <- shrinkRegex' p]
shrinkRegex' (PAny pset) = [PAny pset' | pset' <- shrinkPatternSet pset]
shrinkRegex' (PAnyNot pset) = [PAnyNot pset' | pset' <- shrinkPatternSet pset]
shrinkRegex' (PEscape c) = [PEscape c' | c' <- shrinkChar c]
shrinkRegex' (PBack pi) = [PBack pi' | pi' <- shrinkPatternIndex pi]
shrinkRegex' (PChar c) = [PChar c' | c' <- shrinkChar c]
shrinkRegex' (PString str) = [PString str' | str' <- shrinkString str]
shrinkInt x = [x]
shrinkMaybe x = [x]
shrinkPatternSet x = [x]
shrinkPatternIndex x = [x]
shrinkChar c = [c]
shrinkString = subsequences
shrinkListOfPattern xs = map shrinkRegex' xs
mencode :: Regex -> LC8.ByteString
mencode x = LC8.pack $ "/" ++ showPattern x ++ "/"
regexInfo :: FormatInfo Regex NoActions
regexInfo = def
{ encode = mencode
, random = arbitrary
, value = show
, shrink = shrinkRegex
, ext = "regex"
}
|
4aba719f43a0cbc8bc48e9313705e9eb33c97324aa0fc8e656d13fe9e3e19c3a | danielecapo/sfont | type1.rkt | #lang racket
(require "writepfa.rkt"
"ufopfa.rkt")
(provide
(all-from-out "writepfa.rkt")
(all-from-out "ufopfa.rkt")) | null | https://raw.githubusercontent.com/danielecapo/sfont/c854f9734f15f4c7cd4b98e041b8c961faa3eef2/sfont/export/type1.rkt | racket | #lang racket
(require "writepfa.rkt"
"ufopfa.rkt")
(provide
(all-from-out "writepfa.rkt")
(all-from-out "ufopfa.rkt")) | |
600cba90ce0f7d426dfea86b37c22d0ec9117c4530ed7316621425c60c3b3c25 | iu-parfunc/lvars | UtilInternal.hs |
| A module with helper functions that are used elsewhere in the LVish repository .
module Data.UtilInternal
(
traverseWithKey_,
Traverse_(..)
)
where
import Control.Applicative (Const(..), Applicative, pure, (*>))
import Control.Monad (void)
import Data.Monoid (Monoid(..))
import qualified Data.Map as M
import Prelude ((.))
--------------------------------------------------------------------------------
-- Helper code.
--------------------------------------------------------------------------------
Version of traverseWithKey _ from
( See thread on Haskell - cafe . )
-- Avoids O(N) allocation when traversing for side-effect.
newtype Traverse_ f = Traverse_ { runTraverse_ :: f () }
instance Applicative f => Monoid (Traverse_ f) where
mempty = Traverse_ (pure ())
Traverse_ a `mappend` Traverse_ b = Traverse_ (a *> b)
-- Since the Applicative used is Const (newtype Const m a = Const m), the
-- structure is never built up.
( b ) You can derive traverseWithKey _ from myfoldMapWithKey , e.g. as follows :
{-# INLINE traverseWithKey_ #-}
traverseWithKey_ :: Applicative f => (k -> a -> f ()) -> M.Map k a -> f ()
traverseWithKey_ f = runTraverse_ .
myfoldMapWithKey (\k x -> Traverse_ (void (f k x)))
# INLINE myfoldMapWithKey #
myfoldMapWithKey :: Monoid r => (k -> a -> r) -> M.Map k a -> r
myfoldMapWithKey f = getConst . M.traverseWithKey (\k x -> Const (f k x))
| null | https://raw.githubusercontent.com/iu-parfunc/lvars/78e73c96a929aa75aa4f991d42b2f677849e433a/src/lvish/Data/UtilInternal.hs | haskell | ------------------------------------------------------------------------------
Helper code.
------------------------------------------------------------------------------
Avoids O(N) allocation when traversing for side-effect.
Since the Applicative used is Const (newtype Const m a = Const m), the
structure is never built up.
# INLINE traverseWithKey_ # |
| A module with helper functions that are used elsewhere in the LVish repository .
module Data.UtilInternal
(
traverseWithKey_,
Traverse_(..)
)
where
import Control.Applicative (Const(..), Applicative, pure, (*>))
import Control.Monad (void)
import Data.Monoid (Monoid(..))
import qualified Data.Map as M
import Prelude ((.))
Version of traverseWithKey _ from
( See thread on Haskell - cafe . )
newtype Traverse_ f = Traverse_ { runTraverse_ :: f () }
instance Applicative f => Monoid (Traverse_ f) where
mempty = Traverse_ (pure ())
Traverse_ a `mappend` Traverse_ b = Traverse_ (a *> b)
( b ) You can derive traverseWithKey _ from myfoldMapWithKey , e.g. as follows :
traverseWithKey_ :: Applicative f => (k -> a -> f ()) -> M.Map k a -> f ()
traverseWithKey_ f = runTraverse_ .
myfoldMapWithKey (\k x -> Traverse_ (void (f k x)))
# INLINE myfoldMapWithKey #
myfoldMapWithKey :: Monoid r => (k -> a -> r) -> M.Map k a -> r
myfoldMapWithKey f = getConst . M.traverseWithKey (\k x -> Const (f k x))
|
2b8e9f0a9cab1b9878f8f6612dafe8223fd8800d1495059844af411ddebfd00a | andreasabel/helf | LocallyNamelessSyntax.hs | # LANGUAGE DeriveFunctor #
-- stuff taken from HerBruijnVal
module LocallyNamelessSyntax (BTm(..), DBIndex(..), Annotation(..), toLocallyNameless, fromLocallyNameless) where
import Data.Map (Map)
import qualified Data.Map as Map
import Abstract as A
import Util
import Value
-- * de Bruijn Terms
newtype Annotation a = Annotation { annotation :: a }
deriving (Show, Functor)
instance Eq (Annotation a) where
a == b = True
instance Ord (Annotation a) where
a <= b = True
data DBIndex = DBIndex { index :: Int, identifier :: A.Name }
instance Eq DBIndex where
i == j = index i == index j
instance Show DBIndex where
show (DBIndex i x) = show x ++ "@" ++ show i
instance Ord DBIndex where
compare i j = compare (index i) (index j)
data BTm -- names are only used for quoting
= B DBIndex -- bound variable: de Bruijn index
| BVar A.Name -- free variable: name
| BCon A.Name
| BDef A.Name
| BApp BTm BTm
| BLam (Annotation A.Name) BTm -- name irrelevant for execution
| BConstLam BTm -- these are lambdas, but not counted
| BSort Value.Sort
| BPi BTm BTm
deriving (Eq, Ord)
instance IsApp BTm where
isApp (BApp f e) = Just (f, e)
isApp _ = Nothing
instance Show BTm where
show = show . fromLocallyNameless
fromLocallyNameless :: BTm -> A.Expr
fromLocallyNameless t =
case t of
B i -> Ident $ Var $ identifier i
BVar x -> Ident $ Var x
BCon x -> Ident $ Con x
BDef x -> Ident $ Def x
BApp t u -> App (fromLocallyNameless t) (fromLocallyNameless u)
BPi u (BConstLam t) -> Pi Nothing (fromLocallyNameless u) (fromLocallyNameless t)
BPi u (BLam (Annotation x) t) -> Pi (Just x) (fromLocallyNameless u) (fromLocallyNameless t)
BLam (Annotation x) t -> Lam x Nothing $ fromLocallyNameless t
BConstLam t -> Lam A.noName Nothing $ fromLocallyNameless t
BSort Type -> Typ
impossible : BSort Kind
* transformation , only used for
maybe this should be transferred to Util.hs
data LocBoundList name = LBL {lblsize :: Int, bList :: (Map name Int)}
lbl_empty = LBL 0 (Map.empty)
insert_lbl :: (Ord name) => name -> LocBoundList name -> LocBoundList name
insert_lbl n (LBL k m) = LBL (k+1) (Map.insert n k m) -- note that it does NOT matter whether or not n already had been a key before!
fakeinsert : : ( name ) = > LocBoundList name - > LocBoundList name
fakeinsert ( LBL k m ) = LBL k+1 m
lookup_lbl :: (Ord name) => name -> LocBoundList name -> Maybe Int
lookup_lbl x (LBL _ m)= Map.lookup x m
toLocallyNameless :: A.Expr -> BTm
toLocallyNameless = trans lbl_empty where
trans :: LocBoundList A.Name -> A.Expr -> BTm
trans lbl (Ident ident) = case ident of
Var x -> case lookup_lbl x lbl of
Just k -> B $ DBIndex (lblsize lbl - 1 - k) x
Nothing -> BVar x
Con x -> BCon x
Def x -> BDef x
trans lbl (App e1 e2) = BApp (trans lbl e1) (trans lbl e2)
trans lbl (Lam name _ e) = BLam (Annotation name) $ trans (insert_lbl name lbl) e
trans _ Typ = BSort Type
trans lbl (Pi mname a b) = case mname of
Just n ->
let
a' = trans lbl a
b' = trans lbl $ Lam n Nothing b
in
BPi a' b'
Nothing ->
let
a' = trans lbl a
b' = BConstLam $ trans lbl b
in
BPi a' b'
| null | https://raw.githubusercontent.com/andreasabel/helf/52bc10751f5dac7338adcb085553ba8157692420/src/LocallyNamelessSyntax.hs | haskell | stuff taken from HerBruijnVal
* de Bruijn Terms
names are only used for quoting
bound variable: de Bruijn index
free variable: name
name irrelevant for execution
these are lambdas, but not counted
note that it does NOT matter whether or not n already had been a key before! | # LANGUAGE DeriveFunctor #
module LocallyNamelessSyntax (BTm(..), DBIndex(..), Annotation(..), toLocallyNameless, fromLocallyNameless) where
import Data.Map (Map)
import qualified Data.Map as Map
import Abstract as A
import Util
import Value
newtype Annotation a = Annotation { annotation :: a }
deriving (Show, Functor)
instance Eq (Annotation a) where
a == b = True
instance Ord (Annotation a) where
a <= b = True
data DBIndex = DBIndex { index :: Int, identifier :: A.Name }
instance Eq DBIndex where
i == j = index i == index j
instance Show DBIndex where
show (DBIndex i x) = show x ++ "@" ++ show i
instance Ord DBIndex where
compare i j = compare (index i) (index j)
| BCon A.Name
| BDef A.Name
| BApp BTm BTm
| BSort Value.Sort
| BPi BTm BTm
deriving (Eq, Ord)
instance IsApp BTm where
isApp (BApp f e) = Just (f, e)
isApp _ = Nothing
instance Show BTm where
show = show . fromLocallyNameless
fromLocallyNameless :: BTm -> A.Expr
fromLocallyNameless t =
case t of
B i -> Ident $ Var $ identifier i
BVar x -> Ident $ Var x
BCon x -> Ident $ Con x
BDef x -> Ident $ Def x
BApp t u -> App (fromLocallyNameless t) (fromLocallyNameless u)
BPi u (BConstLam t) -> Pi Nothing (fromLocallyNameless u) (fromLocallyNameless t)
BPi u (BLam (Annotation x) t) -> Pi (Just x) (fromLocallyNameless u) (fromLocallyNameless t)
BLam (Annotation x) t -> Lam x Nothing $ fromLocallyNameless t
BConstLam t -> Lam A.noName Nothing $ fromLocallyNameless t
BSort Type -> Typ
impossible : BSort Kind
* transformation , only used for
maybe this should be transferred to Util.hs
data LocBoundList name = LBL {lblsize :: Int, bList :: (Map name Int)}
lbl_empty = LBL 0 (Map.empty)
insert_lbl :: (Ord name) => name -> LocBoundList name -> LocBoundList name
fakeinsert : : ( name ) = > LocBoundList name - > LocBoundList name
fakeinsert ( LBL k m ) = LBL k+1 m
lookup_lbl :: (Ord name) => name -> LocBoundList name -> Maybe Int
lookup_lbl x (LBL _ m)= Map.lookup x m
toLocallyNameless :: A.Expr -> BTm
toLocallyNameless = trans lbl_empty where
trans :: LocBoundList A.Name -> A.Expr -> BTm
trans lbl (Ident ident) = case ident of
Var x -> case lookup_lbl x lbl of
Just k -> B $ DBIndex (lblsize lbl - 1 - k) x
Nothing -> BVar x
Con x -> BCon x
Def x -> BDef x
trans lbl (App e1 e2) = BApp (trans lbl e1) (trans lbl e2)
trans lbl (Lam name _ e) = BLam (Annotation name) $ trans (insert_lbl name lbl) e
trans _ Typ = BSort Type
trans lbl (Pi mname a b) = case mname of
Just n ->
let
a' = trans lbl a
b' = trans lbl $ Lam n Nothing b
in
BPi a' b'
Nothing ->
let
a' = trans lbl a
b' = BConstLam $ trans lbl b
in
BPi a' b'
|
c8f8a49929061501f55b0b94ec7e6da3aabfb99248fd9971026a7dbf1f8ba905 | dbuenzli/topkg | browse.mli | ---------------------------------------------------------------------------
Copyright ( c ) 2016 . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
% % NAME%% % % ---------------------------------------------------------------------------
Copyright (c) 2016 Daniel C. Bünzli. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
%%NAME%% %%VERSION%%
---------------------------------------------------------------------------*)
(** The [browse] command. *)
val cmd : int Cmdliner.Term.t * Cmdliner.Term.info
---------------------------------------------------------------------------
Copyright ( c ) 2016
Permission to use , copy , modify , and/or distribute this software for any
purpose with or without fee is hereby granted , provided that the above
copyright notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
---------------------------------------------------------------------------
Copyright (c) 2016 Daniel C. Bünzli
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------------*)
| null | https://raw.githubusercontent.com/dbuenzli/topkg/ea1e0981a18ce4160ec21e8a73f67cb748059671/src-bin/browse.mli | ocaml | * The [browse] command. | ---------------------------------------------------------------------------
Copyright ( c ) 2016 . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
% % NAME%% % % ---------------------------------------------------------------------------
Copyright (c) 2016 Daniel C. Bünzli. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
%%NAME%% %%VERSION%%
---------------------------------------------------------------------------*)
val cmd : int Cmdliner.Term.t * Cmdliner.Term.info
---------------------------------------------------------------------------
Copyright ( c ) 2016
Permission to use , copy , modify , and/or distribute this software for any
purpose with or without fee is hereby granted , provided that the above
copyright notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
---------------------------------------------------------------------------
Copyright (c) 2016 Daniel C. Bünzli
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------------*)
|
3c6f4cf0cee38ecdd63452434778830650982484734bf00b4317ec6e164e7cb5 | GaloisInc/daedalus | test.hs | #!/usr/bin/env runhaskell
{-# Language BlockArguments #-}
{-# Language ImplicitParams #-}
{-# Language ConstraintKinds #-}
module Main where
import Text.Read(readMaybe)
import Data.Maybe
import Data.List
import Data.Char
import Control.Monad(filterM,forM)
import Control.Exception(SomeException(..),catch)
import System.FilePath
import System.Process
import System.Directory
import System.Environment
import System.IO
import System.Exit(exitFailure,exitSuccess)
main :: IO ()
main =
do args <- getArgs
let ?verbosity = 1
case args of
"compile" : fs ->
case fs of
[file] -> compile file
_ -> putStrLn "Usage: compile DDL_FILE"
"run" : fs ->
case fs of
[file] -> run file Nothing
[file,input] -> run file (Just input)
_ -> putStrLn "Usage: run DDL_FILE [INPUT]"
"check" : fs ->
case fs of
[file] -> validate file Nothing
[file,input] -> validate file (Just input)
_ -> putStrLn "Usage: check DDL_FILE [INPUT]"
"diff" : fs->
case fs of
a : b : f : rest
| Just be1 <- readMaybe a
, Just be2 <- readMaybe b
-> case rest of
[] -> diff be1 be2 f Nothing
[input] -> diff be1 be2 f (Just input)
_ -> putStrLn
"Usage: diff BACKEND1 BACKEND2 DDL_FILE [INPUT]"
_ -> putStrLn "Usage: diff BACKEND1 BACKEND2 DDL_FILE [INPUT]"
"all" : fs ->
case fs of
[] -> do let ?verbosity = 1
doAllTests
_ -> putStrLn "Usage: all"
"clean" : fs ->
case fs of
[] -> clean
_ -> putStrLn "Usage: clean"
[ file ] -> allPhases file Nothing
[ file, input ] -> allPhases file (Just input)
_ -> mapM_ putStrLn
[ "Usage:"
, " DDL_FILE [INPUT]"
, " compile DDL_FILE"
, " run DDL_FILE [INPUT]"
, " check DDL_FILE [INPUT]"
, " diff BACKEND1 BACKEND2 DDL_FILE [INPUT]"
, " all"
, " clean"
]
type Quiet = (?verbosity :: Int)
data TestResult = OK | OutputsDiffer [[Backend]] | Fail SomeException
deriving Show
isOK :: TestResult -> Bool
isOK result =
case result of
OK -> True
_ -> False
--------------------------------------------------------------------------------
allPhases :: Quiet => FilePath -> Maybe FilePath -> IO ()
allPhases file mbInp =
do compile file
run file mbInp
validate file mbInp
--------------------------------------------------------------------------------
-- Compilation
compile :: Quiet => FilePath -> IO ()
compile file = mapM_ (`compileWith` file) allBackends
compileWith :: Quiet => Backend -> FilePath -> IO ()
compileWith be ddl =
do putStrLn ("[COMPILE " ++ show be ++ "] " ++ ddl)
case be of
InterpDaedalus -> pure ()
InterpCore -> pure ()
InterpVM -> pure ()
CompileHaskell -> compileHaskell ddl
CompileCPP -> compileCPP ddl
compileHaskell :: Quiet => FilePath -> IO ()
compileHaskell ddl =
do let root = buildRootDirFor CompileHaskell
build = buildDirFor CompileHaskell ddl
createDirectoryIfMissing True build
callProcess' "cp" ["template_cabal_project", root </> "cabal.project"]
callProcess' "cabal"
[ "run", "-v0", "exe:daedalus", "--"
, "compile-hs", "--out-dir=" ++ build, ddl
]
callProcessIn_ build "cabal" ["build"]
callProcessIn_ build "rm" ["-f", "parser"]
path <- callProcessIn build "cabal" [ "-v0", "exec", "which", short ddl ]
callProcessIn_ build "ln" ["-s", head (lines path), "parser"]
pure ()
compileCPP :: Quiet => FilePath -> IO ()
compileCPP ddl =
do let build = buildDirFor CompileCPP ddl
createDirectoryIfMissing True build
callProcess' "cabal"
[ "run", "-v0", "exe:daedalus", "--"
, "compile-c++", "--out-dir=" ++ build, ddl
]
callProcess' "make" [ "-C", build, "parser" ]
--------------------------------------------------------------------------------
-- Running
run :: FilePath -> Maybe FilePath -> IO ()
run ddl mbInput = mapM_ (\be -> runWith be ddl mbInput) allBackends
runWith :: Backend -> FilePath -> Maybe FilePath -> IO ()
runWith be ddl mbInput =
do putStrLn $ unwords [ "[RUN " ++ show be ++ "]", ddl, fromMaybe "" mbInput ]
let file = outputFileFor be ddl mbInput
createDirectoryIfMissing True (takeDirectory file)
let interp = [ "run", "-v0", "exe:daedalus", "--"
, "--no-warn-unbiased", "run", "--json"
]
save file =<<
case be of
InterpDaedalus ->
readProcessWithExitCode "cabal" (interp ++ [ ddl ] ++ inp) ""
InterpCore ->
readProcessWithExitCode "cabal" (interp ++ ["--core", ddl] ++ inp) ""
InterpVM ->
readProcessWithExitCode "cabal" (interp ++ ["--vm", ddl] ++ inp) ""
CompileHaskell ->
readProcessWithExitCode (buildDirFor be ddl </> "parser")
(maybeToList mbInput)
""
CompileCPP ->
readProcessWithExitCode (buildDirFor be ddl </> "parser")
(maybeToList mbInput)
""
where
inp = case mbInput of
Nothing -> []
Just input -> ["--input=" ++ input]
save f (_,o,_) = writeFile f o
--------------------------------------------------------------------------------
-- Validation
equiv :: Eq b => [(a,b)] -> [[a]]
equiv xs0 =
case xs0 of
[] -> []
(x,b) : xs ->
case partition ((== b) . snd) xs of
(as,bs) -> (x : map fst as) : equiv bs
load :: Backend -> FilePath -> Maybe FilePath -> IO (Backend,String)
load be ddl mbInput =
do let file = outputFileFor be ddl mbInput
txt <- readProcess "jq" [".",file] ""
`catch` \SomeException{} ->
do putStrLn ("Failed to parse output: " ++ show file)
putStrLn =<< readFile file
pure ""
pure (be,txt)
validate :: FilePath -> Maybe FilePath -> IO ()
validate x y = validate' x y >> pure ()
validate' :: FilePath -> Maybe FilePath -> IO TestResult
validate' ddl mbInput =
do results <- mapM (\be -> load be ddl mbInput) allBackends
case equiv results of
[_] -> putStrLn "OK" >> pure OK
rs -> do putStrLn "DIFFERENT"
mapM_ (putStrLn . unwords . map show) rs
pure (OutputsDiffer rs)
--------------------------------------------------------------------------------
-- Diff
diff :: Backend -> Backend -> FilePath -> Maybe FilePath -> IO ()
diff be1 be2 ddl mbInput =
do f1 <- formatted be1
f2 <- formatted be2
(_,out,_) <- readProcessWithExitCode "diff" [f1,f2] ""
putStrLn out
removeFile f1
removeFile f2
where
formatted be =
do (f,h) <- openTempFile "/tmp" "diff"
txt <- readProcess "jq" [".", outputFileFor be ddl mbInput] ""
hPutStr h txt
hClose h
pure f
--------------------------------------------------------------------------------
-- Cleaning
clean :: IO ()
clean =
do removeDirectoryRecursive buildDir
removeDirectoryRecursive outputDir
--------------------------------------------------------------------------------
-- Run all tests
doAllTests :: Quiet => IO ()
doAllTests =
do rs <- doAllTestsIn testsDir
let (good,bad) = partition isOK rs
ok = length good
notOk = length bad
total = ok + notOk
putStrLn ("Passed " ++ show ok ++ " / " ++ show total)
if notOk > 0 then exitFailure else exitSuccess
doAllTestsIn :: Quiet => FilePath -> IO [TestResult]
doAllTestsIn dirName =
do files <- listDirectory dirName
if "Main.ddl" `elem` files
then doOneTestInDir files
else concat <$>
forM files \f ->
do let file = dirName </> f
isDir <- doesDirectoryExist file
if isDir
then doAllTestsIn file
else if takeExtension f == ".ddl"
then doOneTest f =<< findInputsFile files f
else pure []
where
findInputsFile siblings file =
do let root = dropExtension file
let inputDir = dirName </> root
hasInput <- doesDirectoryExist inputDir
fs1 <- if hasInput
then do fs <- listDirectory inputDir
pure (map (inputDir </>) fs)
else pure []
let fs2' = [ dirName </> f
| f <- siblings, takeExtension f /= ".ddl" &&
dropExtensions f == root ]
fs2 <- filterM doesFileExist fs2'
pure (fs1 ++ fs2)
doOneTest ddl ins =
attempt
do putStrLn ("--- " ++ ddl ++ " ------------------------------------------")
let file = dirName </> ddl
compile file
case ins of
[] -> attempt
do run file Nothing
(:[]) <$> validate' file Nothing
_ -> concat <$>
forM ins \i ->
attempt
do run file (Just i)
(:[]) <$> validate' file (Just i)
-- XXX
doOneTestInDir siblings = error "Not yet implemented"
attempt m = m `catch` \e@SomeException{} ->
do print e
pure [Fail e]
--------------------------------------------------------------------------------
-- Directory structure
testsDir :: FilePath
testsDir = "tests"
buildDir :: FilePath
buildDir = "build"
outputDir :: FilePath
outputDir = "output"
data Backend = InterpDaedalus
| InterpCore
| InterpVM
| CompileHaskell
| CompileCPP
deriving (Eq,Ord,Enum,Bounded,Show,Read)
allBackends :: [Backend]
allBackends = [ minBound .. maxBound ]
buildRootDirFor :: Backend -> FilePath
buildRootDirFor be = buildDir </> show be
buildDirFor :: Backend -> FilePath -> FilePath
buildDirFor be ddl = buildRootDirFor be </> short ddl
outputFileFor :: Backend -> FilePath -> Maybe FilePath -> FilePath
outputFileFor be ddl mbInput =
outputDir </> short ddl </> maybe "" short mbInput </> show be
--------------------------------------------------------------------------------
Utilities
callProcessIn_ :: Quiet => FilePath -> String -> [String] -> IO ()
callProcessIn_ dir f xs =
do _ <- callProcessIn dir f xs
pure ()
callProcessIn :: Quiet => FilePath -> String -> [String] -> IO String
callProcessIn dir f xs =
do verbose f xs
(_exit,stdout,err) <-
readCreateProcessWithExitCode (proc f xs) { cwd = Just dir } ""
quiet err
pure stdout
callProcess' :: Quiet => FilePath -> [String] -> IO ()
callProcess' f xs =
do verbose f xs
(_,out,err) <- readCreateProcessWithExitCode (proc f xs) ""
quiet out
quiet err
pure ()
verbose :: Quiet => String -> [String] -> IO ()
verbose f xs
| ?verbosity > 1 = putStrLn (unwords (map esc (f : xs)))
| otherwise = pure ()
where
escChar c = isSpace c || c == '"'
esc s = if any escChar s then show s else s
quiet :: Quiet => String -> IO ()
quiet err
| ?verbosity < 1 = pure ()
| otherwise = hPutStr stderr err >> hFlush stderr
short :: FilePath -> String
short = dropExtension . takeFileName
| null | https://raw.githubusercontent.com/GaloisInc/daedalus/7dcbf6a240dedd8473bb18c47dd7e1ed2268afeb/test-all-ways/test.hs | haskell | # Language BlockArguments #
# Language ImplicitParams #
# Language ConstraintKinds #
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Compilation
------------------------------------------------------------------------------
Running
------------------------------------------------------------------------------
Validation
------------------------------------------------------------------------------
Diff
------------------------------------------------------------------------------
Cleaning
------------------------------------------------------------------------------
Run all tests
XXX
------------------------------------------------------------------------------
Directory structure
------------------------------------------------------------------------------ | #!/usr/bin/env runhaskell
module Main where
import Text.Read(readMaybe)
import Data.Maybe
import Data.List
import Data.Char
import Control.Monad(filterM,forM)
import Control.Exception(SomeException(..),catch)
import System.FilePath
import System.Process
import System.Directory
import System.Environment
import System.IO
import System.Exit(exitFailure,exitSuccess)
main :: IO ()
main =
do args <- getArgs
let ?verbosity = 1
case args of
"compile" : fs ->
case fs of
[file] -> compile file
_ -> putStrLn "Usage: compile DDL_FILE"
"run" : fs ->
case fs of
[file] -> run file Nothing
[file,input] -> run file (Just input)
_ -> putStrLn "Usage: run DDL_FILE [INPUT]"
"check" : fs ->
case fs of
[file] -> validate file Nothing
[file,input] -> validate file (Just input)
_ -> putStrLn "Usage: check DDL_FILE [INPUT]"
"diff" : fs->
case fs of
a : b : f : rest
| Just be1 <- readMaybe a
, Just be2 <- readMaybe b
-> case rest of
[] -> diff be1 be2 f Nothing
[input] -> diff be1 be2 f (Just input)
_ -> putStrLn
"Usage: diff BACKEND1 BACKEND2 DDL_FILE [INPUT]"
_ -> putStrLn "Usage: diff BACKEND1 BACKEND2 DDL_FILE [INPUT]"
"all" : fs ->
case fs of
[] -> do let ?verbosity = 1
doAllTests
_ -> putStrLn "Usage: all"
"clean" : fs ->
case fs of
[] -> clean
_ -> putStrLn "Usage: clean"
[ file ] -> allPhases file Nothing
[ file, input ] -> allPhases file (Just input)
_ -> mapM_ putStrLn
[ "Usage:"
, " DDL_FILE [INPUT]"
, " compile DDL_FILE"
, " run DDL_FILE [INPUT]"
, " check DDL_FILE [INPUT]"
, " diff BACKEND1 BACKEND2 DDL_FILE [INPUT]"
, " all"
, " clean"
]
type Quiet = (?verbosity :: Int)
data TestResult = OK | OutputsDiffer [[Backend]] | Fail SomeException
deriving Show
isOK :: TestResult -> Bool
isOK result =
case result of
OK -> True
_ -> False
allPhases :: Quiet => FilePath -> Maybe FilePath -> IO ()
allPhases file mbInp =
do compile file
run file mbInp
validate file mbInp
compile :: Quiet => FilePath -> IO ()
compile file = mapM_ (`compileWith` file) allBackends
compileWith :: Quiet => Backend -> FilePath -> IO ()
compileWith be ddl =
do putStrLn ("[COMPILE " ++ show be ++ "] " ++ ddl)
case be of
InterpDaedalus -> pure ()
InterpCore -> pure ()
InterpVM -> pure ()
CompileHaskell -> compileHaskell ddl
CompileCPP -> compileCPP ddl
compileHaskell :: Quiet => FilePath -> IO ()
compileHaskell ddl =
do let root = buildRootDirFor CompileHaskell
build = buildDirFor CompileHaskell ddl
createDirectoryIfMissing True build
callProcess' "cp" ["template_cabal_project", root </> "cabal.project"]
callProcess' "cabal"
[ "run", "-v0", "exe:daedalus", "--"
, "compile-hs", "--out-dir=" ++ build, ddl
]
callProcessIn_ build "cabal" ["build"]
callProcessIn_ build "rm" ["-f", "parser"]
path <- callProcessIn build "cabal" [ "-v0", "exec", "which", short ddl ]
callProcessIn_ build "ln" ["-s", head (lines path), "parser"]
pure ()
compileCPP :: Quiet => FilePath -> IO ()
compileCPP ddl =
do let build = buildDirFor CompileCPP ddl
createDirectoryIfMissing True build
callProcess' "cabal"
[ "run", "-v0", "exe:daedalus", "--"
, "compile-c++", "--out-dir=" ++ build, ddl
]
callProcess' "make" [ "-C", build, "parser" ]
run :: FilePath -> Maybe FilePath -> IO ()
run ddl mbInput = mapM_ (\be -> runWith be ddl mbInput) allBackends
runWith :: Backend -> FilePath -> Maybe FilePath -> IO ()
runWith be ddl mbInput =
do putStrLn $ unwords [ "[RUN " ++ show be ++ "]", ddl, fromMaybe "" mbInput ]
let file = outputFileFor be ddl mbInput
createDirectoryIfMissing True (takeDirectory file)
let interp = [ "run", "-v0", "exe:daedalus", "--"
, "--no-warn-unbiased", "run", "--json"
]
save file =<<
case be of
InterpDaedalus ->
readProcessWithExitCode "cabal" (interp ++ [ ddl ] ++ inp) ""
InterpCore ->
readProcessWithExitCode "cabal" (interp ++ ["--core", ddl] ++ inp) ""
InterpVM ->
readProcessWithExitCode "cabal" (interp ++ ["--vm", ddl] ++ inp) ""
CompileHaskell ->
readProcessWithExitCode (buildDirFor be ddl </> "parser")
(maybeToList mbInput)
""
CompileCPP ->
readProcessWithExitCode (buildDirFor be ddl </> "parser")
(maybeToList mbInput)
""
where
inp = case mbInput of
Nothing -> []
Just input -> ["--input=" ++ input]
save f (_,o,_) = writeFile f o
equiv :: Eq b => [(a,b)] -> [[a]]
equiv xs0 =
case xs0 of
[] -> []
(x,b) : xs ->
case partition ((== b) . snd) xs of
(as,bs) -> (x : map fst as) : equiv bs
load :: Backend -> FilePath -> Maybe FilePath -> IO (Backend,String)
load be ddl mbInput =
do let file = outputFileFor be ddl mbInput
txt <- readProcess "jq" [".",file] ""
`catch` \SomeException{} ->
do putStrLn ("Failed to parse output: " ++ show file)
putStrLn =<< readFile file
pure ""
pure (be,txt)
validate :: FilePath -> Maybe FilePath -> IO ()
validate x y = validate' x y >> pure ()
validate' :: FilePath -> Maybe FilePath -> IO TestResult
validate' ddl mbInput =
do results <- mapM (\be -> load be ddl mbInput) allBackends
case equiv results of
[_] -> putStrLn "OK" >> pure OK
rs -> do putStrLn "DIFFERENT"
mapM_ (putStrLn . unwords . map show) rs
pure (OutputsDiffer rs)
diff :: Backend -> Backend -> FilePath -> Maybe FilePath -> IO ()
diff be1 be2 ddl mbInput =
do f1 <- formatted be1
f2 <- formatted be2
(_,out,_) <- readProcessWithExitCode "diff" [f1,f2] ""
putStrLn out
removeFile f1
removeFile f2
where
formatted be =
do (f,h) <- openTempFile "/tmp" "diff"
txt <- readProcess "jq" [".", outputFileFor be ddl mbInput] ""
hPutStr h txt
hClose h
pure f
clean :: IO ()
clean =
do removeDirectoryRecursive buildDir
removeDirectoryRecursive outputDir
doAllTests :: Quiet => IO ()
doAllTests =
do rs <- doAllTestsIn testsDir
let (good,bad) = partition isOK rs
ok = length good
notOk = length bad
total = ok + notOk
putStrLn ("Passed " ++ show ok ++ " / " ++ show total)
if notOk > 0 then exitFailure else exitSuccess
doAllTestsIn :: Quiet => FilePath -> IO [TestResult]
doAllTestsIn dirName =
do files <- listDirectory dirName
if "Main.ddl" `elem` files
then doOneTestInDir files
else concat <$>
forM files \f ->
do let file = dirName </> f
isDir <- doesDirectoryExist file
if isDir
then doAllTestsIn file
else if takeExtension f == ".ddl"
then doOneTest f =<< findInputsFile files f
else pure []
where
findInputsFile siblings file =
do let root = dropExtension file
let inputDir = dirName </> root
hasInput <- doesDirectoryExist inputDir
fs1 <- if hasInput
then do fs <- listDirectory inputDir
pure (map (inputDir </>) fs)
else pure []
let fs2' = [ dirName </> f
| f <- siblings, takeExtension f /= ".ddl" &&
dropExtensions f == root ]
fs2 <- filterM doesFileExist fs2'
pure (fs1 ++ fs2)
doOneTest ddl ins =
attempt
do putStrLn ("--- " ++ ddl ++ " ------------------------------------------")
let file = dirName </> ddl
compile file
case ins of
[] -> attempt
do run file Nothing
(:[]) <$> validate' file Nothing
_ -> concat <$>
forM ins \i ->
attempt
do run file (Just i)
(:[]) <$> validate' file (Just i)
doOneTestInDir siblings = error "Not yet implemented"
attempt m = m `catch` \e@SomeException{} ->
do print e
pure [Fail e]
testsDir :: FilePath
testsDir = "tests"
buildDir :: FilePath
buildDir = "build"
outputDir :: FilePath
outputDir = "output"
data Backend = InterpDaedalus
| InterpCore
| InterpVM
| CompileHaskell
| CompileCPP
deriving (Eq,Ord,Enum,Bounded,Show,Read)
allBackends :: [Backend]
allBackends = [ minBound .. maxBound ]
buildRootDirFor :: Backend -> FilePath
buildRootDirFor be = buildDir </> show be
buildDirFor :: Backend -> FilePath -> FilePath
buildDirFor be ddl = buildRootDirFor be </> short ddl
outputFileFor :: Backend -> FilePath -> Maybe FilePath -> FilePath
outputFileFor be ddl mbInput =
outputDir </> short ddl </> maybe "" short mbInput </> show be
Utilities
callProcessIn_ :: Quiet => FilePath -> String -> [String] -> IO ()
callProcessIn_ dir f xs =
do _ <- callProcessIn dir f xs
pure ()
callProcessIn :: Quiet => FilePath -> String -> [String] -> IO String
callProcessIn dir f xs =
do verbose f xs
(_exit,stdout,err) <-
readCreateProcessWithExitCode (proc f xs) { cwd = Just dir } ""
quiet err
pure stdout
callProcess' :: Quiet => FilePath -> [String] -> IO ()
callProcess' f xs =
do verbose f xs
(_,out,err) <- readCreateProcessWithExitCode (proc f xs) ""
quiet out
quiet err
pure ()
verbose :: Quiet => String -> [String] -> IO ()
verbose f xs
| ?verbosity > 1 = putStrLn (unwords (map esc (f : xs)))
| otherwise = pure ()
where
escChar c = isSpace c || c == '"'
esc s = if any escChar s then show s else s
quiet :: Quiet => String -> IO ()
quiet err
| ?verbosity < 1 = pure ()
| otherwise = hPutStr stderr err >> hFlush stderr
short :: FilePath -> String
short = dropExtension . takeFileName
|
172bad6130ce9d1cc5776356f2ba71be45a256206aace95748d429026d2f028e | kfl/adventofcode_2022 | day14.hs | # LANGUAGE LambdaCase #
module Main where
import qualified Data.Char as C
import qualified Data.List as L
import qualified Data.List.Split as S
import Text.ParserCombinators.ReadP
import Control.Monad (forM_)
import Data.Ix
import qualified Data.Array as A
import Data.Array ((!))
test = map parse [ "498,4 -> 498,6 -> 496,6"
, "503,4 -> 502,4 -> 502,9 -> 494,9"
]
input = map parse . lines <$> readFile "input.txt"
type Pos = (Int, Int)
type Line = [Pos]
type Input = [Line]
parse :: String -> Line
parse str = res
where [(res, _)] = readP_to_S (line <* eof) str
int = read <$> munch1 C.isDigit
pos = (,) <$> (int <* char ',') <*> int
line = sepBy1 pos (string " -> ")
data Cell = Empty | Rock | Sand
deriving (Eq, Show)
type Grid = A.Array Pos Cell
toGrid lines = A.accumArray (\ _ x -> x) Empty bnds (zip rocks $ repeat Rock)
where expand prev (next, acc) = (prev, range (min next prev, max next prev) ++ acc)
rocks = concatMap (\line -> concatMap (\[x,y] -> range (min x y, max x y)) $ S.divvy 2 1 line) lines
(xs, ys) = unzip rocks
bnds = ((minimum xs-1, 0), (maximum xs, maximum ys))
showGrid :: Grid -> IO()
showGrid grid = do
forM_ [minY .. maxY] $ \j -> do
forM_ [minX .. maxX] $ \i -> do
putStr $ cell $ grid ! (i,j)
putStrLn ""
where ((minX, minY), (maxX, maxY)) = A.bounds grid
cell = \case Empty -> "."; Rock -> "#" ; _ -> "o"
toRest grid = \case
(i, j) | not $ bnds `A.inRange` (i, j+1) -> Nothing
(i, j) | grid ! (i, j+1) == Empty -> toRest grid (i, j+1)
(i, j) | grid ! (i-1, j+1) == Empty -> toRest grid (i-1, j+1)
(i, j) | grid ! (i+1, j+1) == Empty -> toRest grid (i+1, j+1)
idx -> Just idx
where bnds = A.bounds grid
step toRest grid = fmap (\idx -> grid A.// [(idx, Sand)]) $ toRest grid (500,0)
stages toRest grid = L.unfoldr (\g -> case step toRest g of
Nothing -> Nothing
Just g' -> Just (g, g')) grid
part1, part2 :: Input -> Int
part1 input = length . stages toRest . toGrid $ input
answer1 = part1 <$> input
toRest2 grid = \case
(i, j) | grid ! (500, 0) /= Empty -> Nothing
(i, j) | grid ! (i, j+1) == Empty -> toRest2 grid (i, j+1)
(i, j) | grid ! (i-1, j+1) == Empty -> toRest2 grid (i-1, j+1)
(i, j) | grid ! (i+1, j+1) == Empty -> toRest2 grid (i+1, j+1)
idx -> Just idx
where bnds = A.bounds grid
addFloor grid = A.accumArray (\ _ x -> x) Empty bnds $ floor ++ A.assocs grid
where ((lx,ly), (ux, uy)) = A.bounds grid
bnds@((lx', _), (ux', uy')) = ((lx-uy-10, ly), (ux+uy+10, uy+2))
floor = [(i, Rock) | i <- range ((lx', uy'), (ux', uy'))]
part2 input = length . stages toRest2 . addFloor . toGrid $ input
answer2 = part2 <$> input
main = do
inp <- input
print $ part1 inp
print $ part2 inp
| null | https://raw.githubusercontent.com/kfl/adventofcode_2022/82a7cb39c600b6228bd6d1e643acdc8b9cc1b961/day14/day14.hs | haskell | # LANGUAGE LambdaCase #
module Main where
import qualified Data.Char as C
import qualified Data.List as L
import qualified Data.List.Split as S
import Text.ParserCombinators.ReadP
import Control.Monad (forM_)
import Data.Ix
import qualified Data.Array as A
import Data.Array ((!))
test = map parse [ "498,4 -> 498,6 -> 496,6"
, "503,4 -> 502,4 -> 502,9 -> 494,9"
]
input = map parse . lines <$> readFile "input.txt"
type Pos = (Int, Int)
type Line = [Pos]
type Input = [Line]
parse :: String -> Line
parse str = res
where [(res, _)] = readP_to_S (line <* eof) str
int = read <$> munch1 C.isDigit
pos = (,) <$> (int <* char ',') <*> int
line = sepBy1 pos (string " -> ")
data Cell = Empty | Rock | Sand
deriving (Eq, Show)
type Grid = A.Array Pos Cell
toGrid lines = A.accumArray (\ _ x -> x) Empty bnds (zip rocks $ repeat Rock)
where expand prev (next, acc) = (prev, range (min next prev, max next prev) ++ acc)
rocks = concatMap (\line -> concatMap (\[x,y] -> range (min x y, max x y)) $ S.divvy 2 1 line) lines
(xs, ys) = unzip rocks
bnds = ((minimum xs-1, 0), (maximum xs, maximum ys))
showGrid :: Grid -> IO()
showGrid grid = do
forM_ [minY .. maxY] $ \j -> do
forM_ [minX .. maxX] $ \i -> do
putStr $ cell $ grid ! (i,j)
putStrLn ""
where ((minX, minY), (maxX, maxY)) = A.bounds grid
cell = \case Empty -> "."; Rock -> "#" ; _ -> "o"
toRest grid = \case
(i, j) | not $ bnds `A.inRange` (i, j+1) -> Nothing
(i, j) | grid ! (i, j+1) == Empty -> toRest grid (i, j+1)
(i, j) | grid ! (i-1, j+1) == Empty -> toRest grid (i-1, j+1)
(i, j) | grid ! (i+1, j+1) == Empty -> toRest grid (i+1, j+1)
idx -> Just idx
where bnds = A.bounds grid
step toRest grid = fmap (\idx -> grid A.// [(idx, Sand)]) $ toRest grid (500,0)
stages toRest grid = L.unfoldr (\g -> case step toRest g of
Nothing -> Nothing
Just g' -> Just (g, g')) grid
part1, part2 :: Input -> Int
part1 input = length . stages toRest . toGrid $ input
answer1 = part1 <$> input
toRest2 grid = \case
(i, j) | grid ! (500, 0) /= Empty -> Nothing
(i, j) | grid ! (i, j+1) == Empty -> toRest2 grid (i, j+1)
(i, j) | grid ! (i-1, j+1) == Empty -> toRest2 grid (i-1, j+1)
(i, j) | grid ! (i+1, j+1) == Empty -> toRest2 grid (i+1, j+1)
idx -> Just idx
where bnds = A.bounds grid
addFloor grid = A.accumArray (\ _ x -> x) Empty bnds $ floor ++ A.assocs grid
where ((lx,ly), (ux, uy)) = A.bounds grid
bnds@((lx', _), (ux', uy')) = ((lx-uy-10, ly), (ux+uy+10, uy+2))
floor = [(i, Rock) | i <- range ((lx', uy'), (ux', uy'))]
part2 input = length . stages toRest2 . addFloor . toGrid $ input
answer2 = part2 <$> input
main = do
inp <- input
print $ part1 inp
print $ part2 inp
| |
5f7ffe33126f2b7a0d478197bb850fff7dc3f98dd235c2001cad6dd56488aa7a | taylorwood/lein-native-image | project.clj | (defproject http-api "0.1.0-SNAPSHOT"
:dependencies [[org.clojure/clojure "1.9.0"]
[http-kit "2.3.0"]
[ring/ring-core "1.6.3"]
[ring/ring-json "0.4.0"]
[compojure "1.6.1"]
[clj-http-lite "0.3.0"]
[hickory "0.7.1"]]
:plugins [[io.taylorwood/lein-native-image "0.3.1"]]
:target-path "target/%s"
:native-image {:graal-bin :env/GRAALVM_HOME
:opts ["-H:EnableURLProtocols=http"
"--report-unsupported-elements-at-runtime" ;; ignore native-image build errors
"--initialize-at-build-time"
"--verbose"]
:name "server"}
:main http-api.core
:profiles {:dev {:dependencies [[org.clojure/test.check "0.9.0"]]}
:native-image {:jvm-opts ["-Dclojure.compiler.direct-linking=true"]}
:uberjar {:aot :all}})
| null | https://raw.githubusercontent.com/taylorwood/lein-native-image/4c45d7a0ee2de91955f1b0515cd32ac50e782ba1/examples/http-api/project.clj | clojure | ignore native-image build errors | (defproject http-api "0.1.0-SNAPSHOT"
:dependencies [[org.clojure/clojure "1.9.0"]
[http-kit "2.3.0"]
[ring/ring-core "1.6.3"]
[ring/ring-json "0.4.0"]
[compojure "1.6.1"]
[clj-http-lite "0.3.0"]
[hickory "0.7.1"]]
:plugins [[io.taylorwood/lein-native-image "0.3.1"]]
:target-path "target/%s"
:native-image {:graal-bin :env/GRAALVM_HOME
:opts ["-H:EnableURLProtocols=http"
"--initialize-at-build-time"
"--verbose"]
:name "server"}
:main http-api.core
:profiles {:dev {:dependencies [[org.clojure/test.check "0.9.0"]]}
:native-image {:jvm-opts ["-Dclojure.compiler.direct-linking=true"]}
:uberjar {:aot :all}})
|
d80cf2179af4bf519ac05d6d80b71095e91f801834fb604bc04a75f9581674ac | hamidreza-s/Tecipe | tecipe_listener_sup.erl | -module(tecipe_listener_sup).
-behaviour(supervisor).
-export([start_link/4]).
-export([init/1]).
-include("tecipe.hrl").
start_link(Ref, Port, Handler, ListenerRec) ->
Name = ListenerRec#tecipe_listener.listener_name,
supervisor:start_link({local, Name}, ?MODULE, [Ref, Port, Handler, ListenerRec]).
init([Ref, Port, Handler, ListenerRec]) ->
Transport = ListenerRec#tecipe_listener.transport,
TransportInitOpts = ListenerRec#tecipe_listener.transport_init_opts,
TransportUserOpts = ListenerRec#tecipe_listener.transport_user_opts,
@NOTE : user options has precedence over default options , so they come first in list
{ok, ListeningSock} = Transport:listen(Port, TransportInitOpts ++ TransportUserOpts),
AcceptorChild =
case ListenerRec#tecipe_listener.acceptor_type of
static ->
{{tecipe_acceptor_static, Ref},
{tecipe_acceptor_static, start_link,
[Ref, Handler, ListeningSock, ListenerRec]},
permanent,
3000,
supervisor,
[tecipe_acceptor_static]};
dynamic ->
{{tecipe_acceptor_dynamic, Ref},
{tecipe_acceptor_dynamic, start_link,
[Ref, Handler, ListeningSock, ListenerRec]},
permanent,
3000,
worker,
[tecipe_acceptor_dynamic]}
end,
MonitorChild = {{tecipe_monitor, Ref},
{tecipe_monitor, start_link, [Ref, ListenerRec]},
permanent,
3000,
worker,
[tecipe_monitor]},
{ok, {{one_for_all, 10, 1}, [MonitorChild, AcceptorChild]}}.
| null | https://raw.githubusercontent.com/hamidreza-s/Tecipe/bcafcafec4c9c5981e6b89537808f3c9e94ea290/src/tecipe_listener_sup.erl | erlang | -module(tecipe_listener_sup).
-behaviour(supervisor).
-export([start_link/4]).
-export([init/1]).
-include("tecipe.hrl").
start_link(Ref, Port, Handler, ListenerRec) ->
Name = ListenerRec#tecipe_listener.listener_name,
supervisor:start_link({local, Name}, ?MODULE, [Ref, Port, Handler, ListenerRec]).
init([Ref, Port, Handler, ListenerRec]) ->
Transport = ListenerRec#tecipe_listener.transport,
TransportInitOpts = ListenerRec#tecipe_listener.transport_init_opts,
TransportUserOpts = ListenerRec#tecipe_listener.transport_user_opts,
@NOTE : user options has precedence over default options , so they come first in list
{ok, ListeningSock} = Transport:listen(Port, TransportInitOpts ++ TransportUserOpts),
AcceptorChild =
case ListenerRec#tecipe_listener.acceptor_type of
static ->
{{tecipe_acceptor_static, Ref},
{tecipe_acceptor_static, start_link,
[Ref, Handler, ListeningSock, ListenerRec]},
permanent,
3000,
supervisor,
[tecipe_acceptor_static]};
dynamic ->
{{tecipe_acceptor_dynamic, Ref},
{tecipe_acceptor_dynamic, start_link,
[Ref, Handler, ListeningSock, ListenerRec]},
permanent,
3000,
worker,
[tecipe_acceptor_dynamic]}
end,
MonitorChild = {{tecipe_monitor, Ref},
{tecipe_monitor, start_link, [Ref, ListenerRec]},
permanent,
3000,
worker,
[tecipe_monitor]},
{ok, {{one_for_all, 10, 1}, [MonitorChild, AcceptorChild]}}.
| |
cc811ec806c66f7fe8154f9c659fc70ebfae489d4ee40eae5114f54d8c5c2faf | junjihashimoto/th-cas | Base.hs | {-#LANGUAGE OverloadedStrings#-}
module Algebra.CAS.Base where
import Data.String
import Data.List(nub)
-- | Mathematical constant expression
data Const =
^ Zero
^ One
| CI Integer -- ^ Integer
^ Faction = CF numer denom
| CR Double -- ^ Real Number
deriving (Eq,Show,Read)
instance Ord Const where
compare Zero Zero = EQ
compare Zero One = LT
compare Zero (CI a) = compare 0 a
compare Zero (CF a b) = compare 0 (a*b)
compare Zero (CR a) = compare 0 a
compare One One = EQ
compare One (CI a) = compare 1 a
compare One (CF a b) = compare 1 (a*b)
compare One (CR a) = compare 1 a
compare (CI a) (CI b) = compare a b
compare (CI a) (CF b c) =
let v = fromIntegral b / fromIntegral c :: Double
in compare (fromIntegral a) v
compare (CI a) (CR b) = compare (fromIntegral a) b
compare (CF a b) (CF c d) =
let v0 = fromIntegral a / fromIntegral b :: Double
v1 = fromIntegral c / fromIntegral d :: Double
in compare v0 v1
compare (CF a b) (CR c) = compare (fromIntegral a / fromIntegral b) c
compare (CR a) (CR b) = compare a b
compare a b =
case compare b a of
LT -> GT
GT -> LT
EQ -> EQ
neg :: Const
neg = CI (-1)
constSimplify :: Const -> Const
constSimplify (CI 0) = Zero
constSimplify (CI 1) = One
constSimplify (CF 0 _) = Zero
constSimplify (CF a 1) = (CI a)
constSimplify (CF a (-1)) = (CI (-a))
constSimplify (CF a b) | a == b = One
| otherwise =
case gcd a b of
1 -> CF a b
g -> constSimplify $ CF (a`div`g) (b`div`g)
constSimplify (CR 0) = Zero
constSimplify (CR 1) = One
constSimplify a = a
instance Num Const where
fromInteger 0 = Zero
fromInteger 1 = One
fromInteger a = CI (fromIntegral a)
(+) a'' b'' =
case (a'',b'') of
(Zero,Zero) -> Zero
(Zero,b) -> b
(One,One) -> CI 2
(One,CI b') -> constSimplify $ CI (1+b')
(One,CF a' b') -> constSimplify $ CF (a'+b') b'
(One,CR b') -> constSimplify $ CR (1+b')
(CI a',CI b') -> constSimplify $ CI (a'+b')
(CI a',CF b' c') -> constSimplify $ CF (b'+c'*a') c'
(CI a',CR b') -> constSimplify $ CR ((fromIntegral a')+b')
(CF a' b',CF c' d') -> constSimplify $ CF (a'*d'+b'*c') (b'*d')
(CF a' b',CR c') -> constSimplify $ CR ((fromIntegral a')/(fromIntegral b')+c')
(CR a',CR b') -> constSimplify $ CR (a'+b')
(a,b) -> (+) b a
(-) a b | a == b = Zero
| otherwise = a + (neg * b)
(*) a'' b'' =
case (a'',b'') of
(Zero,Zero) -> Zero
(Zero,_) -> Zero
(One,One) -> One
(One,a') -> a'
(CI a',CI b') -> constSimplify $ CI (a'*b')
(CI a',CF b' c') -> constSimplify $ CF (b'*a') c'
(CI a',CR b') -> constSimplify $ CR ((fromIntegral a')*b')
(CF a' b',CF c' d') -> constSimplify $ CF (a'*c') (b'*d')
(CF a' b',CR c') -> constSimplify $ CR (fromIntegral a' * c' / fromIntegral b')
(CR a',CR b') -> constSimplify $ CR (a'*b')
(_,Zero) -> Zero
(a',One) -> a'
(a,b) -> (*) b a
abs Zero = Zero
abs One = One
abs (CI a) = CI (abs a)
abs (CF a b) = CF (abs a) (abs b)
abs (CR a) = CR (abs a)
signum Zero = CI 0
signum One = CI (-1)
signum (CI a) = CI (signum a)
signum (CF a b) = CI $ signum a * signum b
signum (CR a) = CI $ round $ signum a
instance Fractional Const where
fromRational 0 = Zero
fromRational 1 = One
fromRational a = CR (fromRational a)
recip a = (/) One a
(/) a' b' =
case (a',b') of
(Zero,_) -> Zero
(_,Zero) -> error "DivideByZero"
(One,One) -> One
(One,CI (-1)) -> CI (-1)
(One,CI a) -> CF 1 a
(One,CF a b) -> CF b a
(One,CR a) -> CR (1/a)
(CI a,CI (-1)) -> CI (-a)
(CI a,CI b) -> constSimplify $ CF a b
(CI a,CF b c) -> constSimplify $ CF (a*c) b
(CI a,CR b) -> constSimplify $ CR (fromIntegral a /b)
(CF a b,CF c d) -> constSimplify $ CF (a*d) (b*c)
(CF a b,CR c) -> constSimplify $ CR (fromIntegral a /fromIntegral b * c)
(CR a,CR b) -> constSimplify $ CR (a/b)
(a,One) -> a
(a,CI (-1)) -> -a
(CF b c,CI a) -> constSimplify $ CF b (a*c)
(CR b,CI a) -> constSimplify $ CR (b/fromIntegral a)
(CR c,CF a b) -> constSimplify $ CR (fromIntegral b /fromIntegral a * c)
instance Enum Const where
succ a = a+1
pred a = a-1
toEnum v = fromIntegral v
fromEnum Zero = 0
fromEnum One = 1
fromEnum (CI a) = fromEnum a
fromEnum (CR a) = fromEnum a
fromEnum (CF a b) = fromEnum ((fromIntegral a::Double) / fromIntegral b)
instance Real Const where
toRational Zero = toRational (0::Int)
toRational One = toRational (1::Int)
toRational (CI v) = toRational v
toRational (CR v) = toRational v
toRational (CF a b) = toRational ((fromIntegral a :: Double) / fromIntegral b)
instance Floating Const where
pi = CR pi
exp Zero = 1
exp a = CR $ exp $ fromRational $ toRational a
sqrt (CI a) | a2 == a = CI a1
| otherwise = CR $ sqrt $ fromRational $ toRational a
where
a0 = sqrt (fromIntegral a) :: Double
a1 = round a0 :: Integer
a2 = a1 * a1
sqrt a = CR $ sqrt $ fromRational $ toRational a
log One = Zero
log a = CR $ log $ fromRational $ toRational a
(**) _ Zero = 1
(**) a One = a
(**) a (CI b) = a^b
(**) a b = CR $ (fromRational $ toRational a :: Double) ** (fromRational $ toRational b :: Double)
logBase a b = CR $ logBase (fromRational $ toRational $ a) (fromRational $ toRational $ b)
sin a = CR $ sin $ fromRational $ toRational a
tan a = CR $ tan $ fromRational $ toRational a
cos a = CR $ cos $ fromRational $ toRational a
asin a = CR $ asin $ fromRational $ toRational a
atan a = CR $ atan $ fromRational $ toRational a
acos a = CR $ acos $ fromRational $ toRational a
sinh a = CR $ sinh $ fromRational $ toRational a
tanh a = CR $ tanh $ fromRational $ toRational a
cosh a = CR $ cosh $ fromRational $ toRational a
asinh a = CR $ asinh $ fromRational $ toRational a
atanh a = CR $ atanh $ fromRational $ toRational a
acosh a = CR $ acosh $ fromRational $ toRational a
toInt :: Const -> Maybe Integer
toInt Zero = Just 0
toInt One = Just 1
toInt (CI a) = Just a
toInt _ = Nothing
mapTuple :: (a -> b) -> (a,a) -> (b,b)
mapTuple f (a,b) = (f a, f b)
instance Integral Const where
quot a b = fst $ quotRem a b
rem a b = snd $ quotRem a b
quotRem a b =
case (toInt a,toInt b) of
(Just a',Just b') -> mapTuple (constSimplify.CI) $ quotRem a' b'
_ -> if a == b then (1,0) else (0,a)
div = quot
mod = rem
toInteger Zero = 0
toInteger One = 1
toInteger (CI a) = toInteger a
toInteger a = error $ "can not do toInteger:" ++ show a
data SpecialFunction =
Sin Formula
| Cos Formula
| Tan Formula
| Sinh Formula
| Cosh Formula
| Tanh Formula
| Asin Formula
| Acos Formula
| Atan Formula
| Asinh Formula
| Acosh Formula
| Atanh Formula
| Exp Formula
| Log Formula
| Abs Formula
| Sig Formula
| LogBase Formula Formula
| Sqrt Formula
| Diff Formula Formula
| Integrate Formula Formula
deriving (Show,Read,Eq,Ord)
-- | Mathematical expression
data Formula =
C Const -- ^ Constant value
| Pi -- ^ Pi
| I -- ^ Imaginary Number
| CV String -- ^ Constant variable which is used to deal variable(V Name) as constant value
| V String -- ^ Variable
| S SpecialFunction -- ^ Special Functions (sin, cos, exp and etc..)
| Formula :^: Formula
| Formula :*: Formula
| Formula :+: Formula
| Formula :/: Formula
deriving (Eq,Read)
(=:) :: Formula -> Formula -> Formula
(=:) a b = a - b
infix 0 =:
instance Ord Formula where
compare (C a) (C b) = compare a b
compare (C _) Pi = LT
compare (C _) I = LT
compare (C _) (CV _) = LT
compare (C _) _ = LT
compare Pi (C _) = GT
compare Pi Pi = EQ
compare Pi I = LT
compare Pi (CV _) = LT
compare Pi _ = LT
compare I (C _) = GT
compare I Pi = GT
compare I I = EQ
compare I (CV _) = LT
compare I _ = LT
compare (CV _) (C _) = GT
compare (CV _) Pi = GT
compare (CV _) I = GT
compare (CV a) (CV b) = compare a b
compare (CV _) _ = LT
compare (V a) (V b) = compare a b
compare (V _) b@(S _) | isConst b = GT
| otherwise = LT
compare a@(V _) (c@(V _):^:d) | a == c = compare 1 d
| otherwise = compare a c
compare (V _) b | isConst b = GT
| otherwise = LT
compare (S a) (S b) = compare a b
compare (a :*: b) (c :*: d) | b == d = compare a c
| otherwise = compare b d
compare (_ :*: b) c | b == c = GT
| otherwise = compare b c
compare a (_ :*: c) | a == c = LT
| otherwise = compare a c
compare (a :^: b) (c :^: d) | a == c = compare b d
| otherwise = compare a c
compare (a :^: b) c | a == c = compare b 1
| otherwise = compare a c
compare a (b :^: c) | a == b = compare 1 c
| otherwise = compare a b
compare (a :+: b) (c :+: d) | b == d = compare a c
| otherwise = compare b d
compare (_ :+: b) c | b == c = GT
| otherwise = compare b c
compare a (b :+: c) | a == c = LT
| otherwise = compare b c
compare (a :/: b) (c :/: d) = compare (a*d) (c*b)
compare (_ :/: b) c = compare b (c*b)
compare a (b :/: c) = compare (a*c) b
compare a b =
case (isConst a,isConst b) of
(True,True) -> EQ
(True,False) -> LT
(False,True) -> GT
(False,False) ->
case compare b a of
LT -> GT
GT -> LT
EQ -> EQ
tryPlus :: Formula -> Formula -> Maybe Formula
tryPlus (C Zero) (C Zero) = Just (C Zero)
tryPlus (C Zero) a = Just a
tryPlus a (C Zero) = Just a
tryPlus (C a) (C b) = Just $ C (a+b)
tryPlus I I = Just $ C (CI 2) :*: I
tryPlus a@(V _) b@(V _) | a == b = Just $ C (CI 2) :*: a
| otherwise = Nothing
tryPlus a@(V _:^: _) b@(V _:^: _) | a == b = Just $ C (CI 2) :*: a
| otherwise = Nothing
tryPlus (a:+:b) c =
case tryPlus b c of
Nothing ->
case tryPlus a c of
Nothing -> Nothing
Just v -> Just $ v + b
Just v -> Just $ a + v
tryPlus (a:*:b) (c:*:d) =
if b == d then
case tryPlus a c of
Nothing -> Nothing
Just v -> Just $ v * b
else
Nothing
tryPlus (a:*:b) d =
if b == d then
case tryPlus a (C One) of
Nothing -> Nothing
Just v -> Just $ v * b
else
Nothing
tryPlus a (c:*:d) =
if a == d then
case tryPlus (C One) c of
Nothing -> Nothing
Just v -> Just $ v * a
else
Nothing
tryPlus _ _ = Nothing
insertPlus :: Formula -> Formula -> Formula
insertPlus a'@(a:+:b) v | v <= b = insertPlus a v :+: b
| otherwise = a':+:v
insertPlus a v | a <= v = a :+: v
| otherwise = v :+: a
-- | try simplification for multiply
--
-- >>> let [x,y] = map V ["x","y"]
-- >>> tryMul (x**(-1)) x
-- Just 1
tryMul :: Formula -> Formula -> Maybe Formula
tryMul I I = Just $ C neg
tryMul (C Zero) _ = Just $ C Zero
tryMul _ (C Zero) = Just $ C Zero
tryMul (C One) a = Just a
tryMul a (C One) = Just a
tryMul (C a) (C b) = Just $ C (a*b)
tryMul a@(V _) b@(V _) | a == b = Just $ a :^: C (CI 2)
| otherwise = Nothing
tryMul (a@(V _):^: b) (c@(V _):^:d) | a == c = Just $ if b+d==0 then 1 else a :^: (b+d)
| otherwise = Nothing
tryMul a@(V _) (c@(V _):^:d) | a == c = Just $ if 1+d == 0 then 1 else a :^: (1+d)
| otherwise = Nothing
tryMul (a@(V _):^: b) c@(V _) | a == c = Just $ if b+1 == 0 then 1 else a :^: (b+1)
| otherwise = Nothing
tryMul (a@(V _):/: b) c | b == c = Just a
| otherwise = Nothing
tryMul (a:*:b) c =
case tryMul b c of
Nothing ->
case tryMul a c of
Nothing -> Nothing
Just v -> Just $ v * b
Just v -> Just $ a * v
tryMul _ _ = Nothing
insertMul :: Formula -> Formula -> Formula
insertMul a'@(a:*:b) v | v <= b = insertMul a v :*: b
| otherwise = a':*:v
insertMul a v | a <= v = a :*: v
| otherwise = v :*: a
constDiv :: Formula -> Formula -> Formula
constDiv a'' b'' =
case (a'',b'') of
(C a',C b') -> C (a'/b')
(C Zero,_) -> C Zero
(_,C Zero) -> error "divide by zero"
(C One,b) -> C One :/: b
(a,C One) -> a
(a,C c) -> C (1/c) * a
(a,b) | a == b -> C One
| otherwise -> a :/: b
splitExp :: Formula -> (Formula,Formula)
splitExp (a:^:b) = (a,b)
splitExp a = (a,1)
divGB :: Formula -> Formula -> Formula
divGB a b = conv $ (ca `constDiv` cb) * divGB' va vb
where
(ca,va) = head' a
(cb,vb) = head' b
head' :: Formula -> (Formula,Formula)
head' v' = var (firstTerm,1)
where
firstTerm = v'
var (c,v) =
if isConst c
then (c,v)
else var (tailMul c,headMul c*v)
conv (a':*:(C One :/: c)) = a':/:c
conv a' = a'
divGB' :: Formula -> Formula -> Formula
divGB' 1 1 = 1
divGB' a 1 = a
divGB' 1 a = 1 `constDiv` a
divGB' a b =
if hva == hvb
then divGB' ta tb * (hva ** (hpa- hpb))
else if hva < hvb
then divGB' a tb `constDiv` (hvb ** hpb)
else divGB' ta b * (hva ** hpa)
where
(hva,hpa) = splitExp $ headMul a
(hvb,hpb) = splitExp $ headMul b
ta = tailMul a
tb = tailMul b
divAll :: Formula -> Formula -> Formula
divAll a b = expand $ t + (h/b)
where
h = headAdd a
t = case (tailAdd a) of
0 -> 0
v -> divAll v b
instance Num Formula where
fromInteger 0 = C Zero
fromInteger 1 = C One
fromInteger a = C $ CI (fromIntegral a)
(+) a (b:+:c) =
case tryPlus a c of
Just v -> v + b
Nothing -> insertPlus a c + b
(+) a b =
case tryPlus a b of
Just v -> v
Nothing -> insertPlus a b
(-) a b | a == b = C Zero
| otherwise = a + (b * (C neg))
(*) a (b:*:c) =
case tryMul a c of
Just v -> v * b
Nothing -> insertMul a c * b
(*) a b =
case tryMul a b of
Just v -> v
Nothing -> insertMul a b
abs a = S (Abs a)
signum a = S (Sig a)
instance Fractional Formula where
fromRational 0 = C Zero
fromRational 1 = C One
fromRational a = C $ CR (fromRational a)
recip a = (/) (C One) a
(/) a b = divGB a b
instance Floating Formula where
pi = Pi
exp (C Zero) = C One
exp a = S $ Exp a
sqrt (C Zero) = 0
sqrt (C One) = 1
sqrt a'@(C (CI a)) | a < 0 = I * sqrt (-a')
| a2 == a = C $ CI a1
| otherwise = S $ Sqrt a'
where
a0 = sqrt (fromIntegral a) :: Double
a1 = round a0 :: Integer
a2 = a1 * a1
sqrt a = S $ Sqrt a
log (C One) = C Zero
log a = S $ Log a
(**) _ (C Zero) = C One
(**) (C (CI a)) (C (CI b)) = C (CI (a^b))
(**) a (C One) = a
(**) a b = (:^:) a b
logBase a b = S $ LogBase a b
sin = S . Sin
tan = S . Tan
cos = S . Cos
asin = S . Asin
atan = S . Atan
acos = S . Acos
sinh = S . Sinh
tanh = S . Tanh
cosh = S . Cosh
asinh = S . Asinh
atanh = S . Atanh
acosh = S . Acosh
instance IsString Formula where
fromString = val
-- | Lift String to variable of Formula
val :: String -> Formula
val v = V v
-- | Lift String to constant of Formula
cval :: String -> Formula
cval v = CV v
instance Enum Formula where
succ a = a+1
pred a = a-1
toEnum v = fromIntegral v
fromEnum (C Zero) = 0
fromEnum (C One) = 1
fromEnum (C (CI a)) = fromIntegral a
fromEnum a = error $ "can not do fromEnum:" ++ show a
instance Real Formula where
toRational (C (CI v)) = toRational v
toRational (C (CR v)) = toRational v
toRational Pi = toRational (pi::Double)
toRational (C Zero) = toRational (0::Int)
toRational (C One) = toRational (1::Int)
toRational _ = toRational (0::Int)
lcmMonomial :: Formula -> Formula -> Formula
lcmMonomial a b = lcmV ca cb * lcmMonomial' va vb
where
(ca,va) = headV a
(cb,vb) = headV b
lcmV :: Formula -> Formula -> Formula
lcmV (C a') (C b') = C (lcm a' b')
lcmV a' b' = a' * b'
lcmMonomial' :: Formula -> Formula -> Formula
lcmMonomial' 1 1 = 1
lcmMonomial' a 1 = a
lcmMonomial' 1 a = a
lcmMonomial' a b =
if hva == hvb
then lcmMonomial' ta tb * (hva ** max hpa hpb)
else if hva < hvb
then lcmMonomial' a tb * (hvb ** hpb)
else lcmMonomial' ta b * (hva ** hpa)
where
(hva,hpa) = splitExp $ headMul a
(hvb,hpb) = splitExp $ headMul b
ta = tailMul a
tb = tailMul b
reduction :: Formula -> Formula -> (Formula,Formula)
reduction f g =
if va == vl
then
if va == 1
then (ca/cb,0)
else
let (a,b) = reduction (expand (f - c*g)) g
in (c+a,b)
else
case mt of
0 -> (0,h)
t -> let (a,b) = reduction t g
in (a,b+h)
where
(ca,va) = headV f
(cb,vb) = headV g
lcm' = lcmMonomial va vb
(cl,vl) = headV lcm'
h = headAdd f
mt = tailAdd f
c = (lcm' / vb)*ca/cb
reductions :: Formula -> [Formula] -> Formula
reductions f [] = f
reductions f (g:gs) =
let (_,b) = reduction f g
in case b of
0 -> 0
c -> expand $ reductions (expand c) gs
instance Integral Formula where
quot a b = fst $ quotRem a b
rem a b = snd $ quotRem a b
quotRem = reduction
div = quot
mod = rem
toInteger (C Zero) = 0
toInteger (C One) = 1
toInteger (C (CI a)) = toInteger a
toInteger a = error $ "can not do toInteger:" ++ show a
degree :: Formula -> Formula
degree (C _) = 0
degree (CV _) = 0
degree (V _) = 1
degree (S (Sin v)) = degree v
degree (S (Cos v)) = degree v
degree (S (Tan v)) = degree v
degree (S (Sinh v)) = degree v
degree (S (Cosh v)) = degree v
degree (S (Tanh v)) = degree v
degree (S (Asin v)) = degree v
degree (S (Acos v)) = degree v
degree (S (Atan v)) = degree v
degree (S (Asinh v)) = degree v
degree (S (Acosh v)) = degree v
degree (S (Atanh v)) = degree v
degree (S (Exp v)) = degree v
degree (S (Log v)) = degree v
degree (S (Abs v)) = degree v
degree (S (Sig v)) = degree v
degree (S (LogBase v0 v1)) = max (degree v0) (degree v1)
degree Pi = 0
degree I = 0
degree (S (Sqrt v)) = degree v
degree (S (Diff v0 v1)) = max (degree v0) (degree v1)
degree (S (Integrate v0 v1)) = max (degree v0) (degree v1)
degree (v0 :^: v1) = v1 * degree v0
degree (v0 :*: v1) = max (degree v0) (degree v1)
degree (v0 :+: v1) = max (degree v0) (degree v1)
degree (v0 :/: v1) = max (degree v0) (degree v1)
converge :: (Formula -> Formula) -> Formula -> Formula
converge func v =
let v' = func v
in if v' == v
then v'
else converge func v'
-- | try to reduce a variable.
-- >>> let [a,b,c] = map CV ["a","b","c"]
-- >>> let [x,y,z] = map V ["x","y","z"]
> > > let [ f0,f1 ] = [ ( 2*x+4*y+4),(x-2*y+1 ) ]
-- >>> f0*f1
-- (1 + x + (-2)*y)*(4 + 2*x + 4*y)
> > > expand $ f0*f1
-- 4 + 6*x + 2*(x^2) + (-4)*y + (-8)*(y^2)
-- >>> expand $ (a*x-2*b*y+c)
-- c + a*x + (-2)*b*y
-- >>> expand $ - ((-2*b)/(4*b))
-- (-1)*(((-2)*b)/(4*b))
-- >>> expand $ - ((-2*b)/(4*b))*(2*a*x+4*b*y+4*c)
-- (-4)*(((-2)*b)/(4*b))*c + (-2)*a*(((-2)*b)/(4*b))*x + (-4)*(((-2)*b)/(4*b))*b*y
-- >>> expand $ (a*x-2*b*y+c) - ((-2*b)/(4*b))*(2*a*x+4*b*y+4*c)
-- c + (-4)*c*(((-2)*b)/(4*b)) + a*x + (-2)*(((-2)*b)/(4*b))*a*x + (-4)*b*(((-2)*b)/(4*b))*y + (-2)*b*y
expand :: Formula -> Formula
expand f = expand' 100 f
expand' :: Int -- ^ a number of repetition of expanding formula
-> Formula -- ^ original formula
-> Formula -- ^ expanded formula
expand' d f | d <= 0 = f
| otherwise =
case f of
((a:+:b):*:c) -> let (a',b',c') = (expand' (d-1) a,expand' (d-1) b,expand' (d-1) c) in expand' (d-1) (a'*c') + expand' (d-1) (b'*c')
(a:*:(b:+:c)) -> let (a',b',c') = (expand' (d-1) a,expand' (d-1) b,expand' (d-1) c) in expand' (d-1) (a'*b') + expand' (d-1) (a'*c')
(a:+:b) -> let (a',b') = (expand' (d-1) a,expand' (d-1) b) in a'+b'
c@(a:*:b) -> let (a',b') = (expand' (d-1) a,expand' (d-1) b)
c' = a'*b'
in if c==c' then c' else expand' (d-1) c'
(a:/:1) -> expand' (d-1) a
a -> a
expandIO :: Formula -> IO Formula
expandIO f = do
print f
case f of
((a:+:b):*:c) -> do
print "((a:+:b):*:c)"
print a
print b
print c
a' <- expandIO a
b' <- expandIO b
c' <- expandIO c
ac <- expandIO (a'*c')
bc <- expandIO (b'*c')
return $ ac + bc
(a:*:(b:+:c)) -> do
print "(a:*:(b:+:c))"
print a
print b
print c
a' <- expandIO a
b' <- expandIO b
c' <- expandIO c
ab <- expandIO (a'*b')
ac <- expandIO (a'*c')
return $ ab + ac
(a:+:b) -> do
print "(a:+:b)"
print a
print b
a' <- expandIO a
b' <- expandIO b
return $ a'+b'
c@(a:*:b) -> do
print "(a:*:b)"
print a
print b
a' <- expandIO a
b' <- expandIO b
let c' = a'*b'
if c==c' then return c' else expandIO c'
(a:/:1) -> return $ expand a
a -> return a
gcdPolynomial :: Formula -> Formula -> Formula
gcdPolynomial a b | a == 0 = b
| b == 0 = a
| otherwise =
let (a',b') = if a>=b then (a,b) else (b,a)
r = a' `rem` b'
in case r of
0 -> b'
_ -> if r == a' then 1 else gcdPolynomial r b'
lcmPolynomial :: Formula -> Formula -> Formula
lcmPolynomial a b =
let g = gcdPolynomial a b
d0 = a `div` g
d1 = b `div` g
in expand $ d0*d1*g
headAdd :: Formula -> Formula
headAdd (_ :+: ab) = ab
headAdd ab = ab
tailAdd :: Formula -> Formula
tailAdd (a :+: _) = a
tailAdd _ = 0
mapAdd :: (Formula -> Formula) -> Formula -> Formula
mapAdd func formula =
case t of
0 -> func h
_ -> mapAdd func t + func h
where
h = headAdd formula
t = tailAdd formula
splitAdd :: Formula -> [Formula]
splitAdd formula =
case t of
0 -> [h]
_ -> h : splitAdd t
where
h = headAdd formula
t = tailAdd formula
headMul :: Formula -> Formula
headMul (_ :*: ab) = ab
headMul ab = ab
tailMul :: Formula -> Formula
tailMul (a :*: _) = a
tailMul _ = 1
headDiv :: Formula -> Formula
headDiv (_ :/: ab) = ab
headDiv ab = ab
tailDiv :: Formula -> Maybe Formula
tailDiv (a :/: _) = Just a
tailDiv _ = Nothing
-- | substitute expression
--
-- >>> let [x,y,z] = map V ["x","y","z"]
-- >>> subst [(x,3),(y,5)] $ x+y
8
-- >>> subst [(tan(x),z)] (tan(x)**2+1)
1 + z^2
subst :: [(Formula,Formula)] -- ^ List of tuple(orignal term, new term)
-> Formula -- ^ original formula
-> Formula -- ^ replaced formula
subst [] formula = formula
subst ((org,mod'):other) formula = subst other $ subst' org mod' formula
subst' :: Formula -> Formula -> Formula -> Formula
subst' org new formula =
if org == formula
then new
else case formula of
a@(C _) -> a
a@(CV _) -> a
a@Pi -> a
a@I -> a
a@(V _) -> a
(S (Sin v)) -> S $ Sin $ subst' org new v
(S (Cos v)) -> S $ Cos $ subst' org new v
(S (Tan v)) -> S $ Tan $ subst' org new v
(S (Sinh v)) -> S $ Sinh $ subst' org new v
(S (Cosh v)) -> S $ Cosh $ subst' org new v
(S (Tanh v)) -> S $ Tanh $ subst' org new v
(S (Asin v)) -> S $ Asin $ subst' org new v
(S (Acos v)) -> S $ Acos $ subst' org new v
(S (Atan v)) -> S $ Atan $ subst' org new v
(S (Asinh v)) -> S $ Asinh $ subst' org new v
(S (Acosh v)) -> S $ Acosh $ subst' org new v
(S (Atanh v)) -> S $ Atanh $ subst' org new v
(S (Exp v)) -> S $ Exp $ subst' org new v
(S (Log v)) -> S $ Log $ subst' org new v
(S (Abs v)) -> S $ Abs $ subst' org new v
(S (Sig v)) -> S $ Sig $ subst' org new v
(S (LogBase v1 v2)) -> S $ LogBase (subst' org new v1) (subst' org new v2)
(S (Sqrt v)) -> S $ Sqrt $ subst' org new v
(S (Diff v1 v2)) -> S $ Diff (subst' org new v1) (subst' org new v2)
(S (Integrate v1 v2)) -> S $ Integrate (subst' org new v1) (subst' org new v2)
(a:^:b) -> subst' org new a ** subst' org new b
(a:*:b) -> subst' org new a * subst' org new b
(a:+:b) -> subst' org new a + subst' org new b
(a:/:b) -> subst' org new a / subst' org new b
mapFormula :: (Formula -> Formula) -> Formula -> Formula
mapFormula conv a@(C _) = conv a
mapFormula conv a@(CV _) = conv a
mapFormula conv a@Pi = conv a
mapFormula conv a@I = conv a
mapFormula conv a@(V _) = conv a
mapFormula conv (S (Sin v)) = S $ Sin $ mapFormula conv v
mapFormula conv (S (Cos v)) = S $ Cos $ mapFormula conv v
mapFormula conv (S (Tan v)) = S $ Tan $ mapFormula conv v
mapFormula conv (S (Sinh v)) = S $ Sinh $ mapFormula conv v
mapFormula conv (S (Cosh v)) = S $ Cosh $ mapFormula conv v
mapFormula conv (S (Tanh v)) = S $ Tanh $ mapFormula conv v
mapFormula conv (S (Asin v)) = S $ Asin $ mapFormula conv v
mapFormula conv (S (Acos v)) = S $ Acos $ mapFormula conv v
mapFormula conv (S (Atan v)) = S $ Atan $ mapFormula conv v
mapFormula conv (S (Asinh v)) = S $ Asinh $ mapFormula conv v
mapFormula conv (S (Acosh v)) = S $ Acosh $ mapFormula conv v
mapFormula conv (S (Atanh v)) = S $ Atanh $ mapFormula conv v
mapFormula conv (S (Exp v)) = S $ Exp $ mapFormula conv v
mapFormula conv (S (Log v)) = S $ Log $ mapFormula conv v
mapFormula conv (S (Abs v)) = S $ Abs $ mapFormula conv v
mapFormula conv (S (Sig v)) = S $ Sig $ mapFormula conv v
mapFormula conv (S (LogBase v1 v2)) = S $ LogBase (mapFormula conv v1) (mapFormula conv v2)
mapFormula conv (S (Sqrt v)) = S $ Sqrt $ mapFormula conv v
mapFormula conv (S (Diff v1 v2)) = S $ Diff (mapFormula conv v1) (mapFormula conv v2)
mapFormula conv (S (Integrate v1 v2)) = S $ Integrate (mapFormula conv v1) (mapFormula conv v2)
mapFormula conv (a:^:b) = mapFormula conv a ** mapFormula conv b
mapFormula conv (a:*:b) = mapFormula conv a * mapFormula conv b
mapFormula conv (a:+:b) = mapFormula conv a + mapFormula conv b
mapFormula conv (a:/:b) = mapFormula conv a / mapFormula conv b
-- | When formula does not include variable,
-- isConst returns True.
--
-- >>> let x = "x" :: Formula
-- >>> isConst x
-- False
-- >>> isConst $ sin(x)*3
-- False
> > > isConst $ 3.0 * sin(3.0 )
-- True
isConst :: Formula -> Bool
isConst (C _) = True
isConst (CV _) = True
isConst (V _) = False
isConst (S (Sin v)) = isConst v
isConst (S (Cos v)) = isConst v
isConst (S (Tan v)) = isConst v
isConst (S (Sinh v)) = isConst v
isConst (S (Cosh v)) = isConst v
isConst (S (Tanh v)) = isConst v
isConst (S (Asin v)) = isConst v
isConst (S (Acos v)) = isConst v
isConst (S (Atan v)) = isConst v
isConst (S (Asinh v)) = isConst v
isConst (S (Acosh v)) = isConst v
isConst (S (Atanh v)) = isConst v
isConst (S (Exp v)) = isConst v
isConst (S (Log v)) = isConst v
isConst (S (Abs v)) = isConst v
isConst (S (Sig v)) = isConst v
isConst (S (LogBase v0 v1)) = isConst v0 && isConst v1
isConst Pi = True
isConst I = True
isConst (S (Sqrt v)) = isConst v
isConst (S (Diff v0 v1)) = isConst v0 && isConst v1
isConst (S (Integrate v0 v1)) = isConst v0 && isConst v1
isConst (v0 :^: v1) = isConst v0 && isConst v1
isConst (v0 :*: v1) = isConst v0 && isConst v1
isConst (v0 :+: v1) = isConst v0 && isConst v1
isConst (v0 :/: v1) = isConst v0 && isConst v1
hasVariable :: Formula -> Formula -> Bool
hasVariable f v = elem v $ variables f
isVariable :: Formula -> Bool
isVariable = not.isConst
variables :: Formula -> [Formula]
variables (C _) = []
variables (CV _) = []
variables a@(V _) = [a]
variables (S (Sin v)) = variables v
variables (S (Cos v)) = variables v
variables (S (Tan v)) = variables v
variables (S (Sinh v)) = variables v
variables (S (Cosh v)) = variables v
variables (S (Tanh v)) = variables v
variables (S (Asin v)) = variables v
variables (S (Acos v)) = variables v
variables (S (Atan v)) = variables v
variables (S (Asinh v)) = variables v
variables (S (Acosh v)) = variables v
variables (S (Atanh v)) = variables v
variables (S (Exp v)) = variables v
variables (S (Log v)) = variables v
variables (S (Abs v)) = variables v
variables (S (Sig v)) = variables v
variables (S (LogBase v0 v1)) = variables v0 ++ variables v1
variables Pi = []
variables I = []
variables (S (Sqrt v)) = variables v
variables (S (Diff v0 v1)) = variables v0 ++ variables v1
variables (S (Integrate v0 v1)) = variables v0 ++ variables v1
variables (v0 :^: v1) = variables v0 ++ variables v1
variables (v0 :*: v1) = variables v0 ++ variables v1
variables (v0 :+: v1) = variables v0 ++ variables v1
variables (v0 :/: v1) = variables v0 ++ variables v1
denom :: Formula -> Formula
denom (_ :*: (_:/:b)) = b
denom (_:/:b) = b
denom _ = 1
numer :: Formula -> Formula
numer (a :*: (b:/:_)) = a * b
numer (a:/:_) = a
numer a = a
headV :: Formula -- ^ formula
^ ( coefficient of first term , variables of first term )
headV v' = var (firstTerm,1)
where
firstTerm = headAdd v'
var (c,v) =
if isConst c
then (c,v)
else var (tailMul c,headMul c*v)
| Pretty print for Formula type .
Formula 's show function is the same as this .
ppr :: Formula -> String
ppr (C Zero) = "0"
ppr (C One) = "1"
ppr (C (CI a)) = show a
ppr (C (CF a b)) = show a ++"/"++show b
ppr (C (CR a)) = show a
ppr Pi = "π"
ppr I = "i"
ppr (CV v) = v
ppr (V v) = v
ppr (S (Exp v)) = "e(" ++ ppr v ++")"
ppr (S (Log v)) = "log(" ++ ppr v ++")"
ppr (S (Sqrt v)) = "√(" ++ ppr v ++")"
ppr (S (Diff f x)) = "diff(" ++ ppr f ++","++ppr x++")"
ppr (S (Integrate f x)) ="integrate(" ++ ppr f ++","++ppr x++")"
ppr (S (LogBase a b)) = "log_" ++ ppr a++ "(" ++ppr b ++")"
ppr (S (Sig v)) = "sig(" ++ ppr v ++")"
ppr (S (Abs v)) = "|" ++ ppr v ++"|"
ppr (S (Sin v)) = "sin(" ++ ppr v ++")"
ppr (S (Cos v)) = "cos(" ++ ppr v ++")"
ppr (S (Tan v)) = "tan(" ++ ppr v ++")"
ppr (S (Sinh v)) = "sinh(" ++ ppr v ++")"
ppr (S (Cosh v)) = "cosh(" ++ ppr v ++")"
ppr (S (Tanh v)) = "tanh(" ++ ppr v ++")"
ppr (S (Asin v)) = "asin(" ++ ppr v ++")"
ppr (S (Acos v)) = "acos(" ++ ppr v ++")"
ppr (S (Atan v)) = "atan(" ++ ppr v ++")"
ppr (S (Asinh v)) = "asinh(" ++ ppr v ++")"
ppr (S (Acosh v)) = "acosh(" ++ ppr v ++")"
ppr (S (Atanh v)) = "atanh(" ++ ppr v ++")"
ppr (a:^:b) = ppr a ++"^"++ ppr b
ppr (a'@(_:*:_):*:c) = ppr a'++"*" ++ ppr' c
ppr (a:*:b) = ppr' a ++"*"++ ppr' b
ppr (a:+:b) = ppr a ++" + "++ ppr b
ppr (a:/:b) = "(" ++ ppr a ++")/("++ ppr b ++")"
ppr' :: Formula -> String
ppr' c@(C (CI _)) = if c >= 0 then ppr c else "(" ++ ppr c ++ ")"
ppr' c@(C (CR _)) = if c >= 0 then ppr c else "(" ++ ppr c ++ ")"
ppr' c@I = ppr c
ppr' c@Pi = ppr c
ppr' c@(V _) = ppr c
ppr' c@(CV _) = ppr c
ppr' c = "(" ++ ppr c ++ ")"
instance Show Formula where
show = ppr
| This print shows bare structure of Formula type .
This string can be read by Formula 's read function .
showFormula :: Formula -> String
showFormula (C a) = "C (" ++ show a ++")"
showFormula Pi = "Pi"
showFormula I = "I"
showFormula (CV v) = "CV \"" ++ v ++"\""
showFormula (V v) = "V \"" ++ v ++"\""
showFormula (S a) = "S (" ++ show a ++")"
showFormula (a:^:b) = "(" ++ showFormula a ++" :^: "++ showFormula b ++")"
showFormula (a:*:b) = "(" ++ showFormula a ++" :*: "++ showFormula b ++")"
showFormula (a:+:b) = "(" ++ showFormula a ++" :+: "++ showFormula b ++")"
showFormula (a:/:b) = "(" ++ showFormula a ++" :/: "++ showFormula b ++")"
genCoeff :: String -> Int -> [Formula]
genCoeff prefix a = genCoeff' prefix a
where
len = fromIntegral (round (logBase 10 (fromIntegral a))) :: Int
nstr n =
let str = show n
l = length str
in take (len-l) (repeat '0') ++ str
genCoeff' prefix' a' | a' <=0 = []
| otherwise = CV (prefix' ++ nstr (pred a')) : genCoeff' prefix' (pred a')
genVars :: String -> Int -> [Formula]
genVars prefix a = gen' prefix a
where
len = fromIntegral (round (logBase 10 (fromIntegral a))) :: Int
nstr n =
let str = show n
l = length str
in take (len-l) (repeat '0') ++ str
gen' prefix' a' | a' <=0 = []
| otherwise = V (prefix' ++ nstr (pred a')) : gen' prefix' (pred a')
-- | Find indeterminates of an expression
--
-- >>> let [x,y,z] = map V ["x","y","z"]
-- >>> indets (x*y+z/x)
-- [x,y,z]
> > > indets ( 3*x^2 - x*y - y^2 )
-- [x,y]
-- >>> indets (sin(x)*cos(x)**2)
[ sin(x),x , cos(x ) ]
indets :: Formula -> [Formula]
indets = nub.indets'
indets' :: Formula -> [Formula]
indets' (C _) = []
indets' (CV _) = []
indets' a@(V _) = [a]
indets' a@(S (Sin v)) = a:indets' v
indets' a@(S (Cos v)) = a:indets' v
indets' a@(S (Tan v)) = a:indets' v
indets' a@(S (Sinh v)) = a:indets' v
indets' a@(S (Cosh v)) = a:indets' v
indets' a@(S (Tanh v)) = a:indets' v
indets' a@(S (Asin v)) = a:indets' v
indets' a@(S (Acos v)) = a:indets' v
indets' a@(S (Atan v)) = a:indets' v
indets' a@(S (Asinh v)) = a:indets' v
indets' a@(S (Acosh v)) = a:indets' v
indets' a@(S (Atanh v)) = a:indets' v
indets' a@(S (Exp v)) = a:indets' v
indets' a@(S (Log v)) = a:indets' v
indets' a@(S (Abs v)) = a:indets' v
indets' a@(S (Sig v)) = a:indets' v
indets' a@(S (LogBase v0 v1)) = a:indets' v0 ++ a:indets' v1
indets' Pi = []
indets' I = []
indets' a@(S (Sqrt v)) = a:indets' v
indets' a@(S (Diff v0 v1)) = (a:indets' v0) ++ indets' v1
indets' a@(S (Integrate v0 v1)) = (a:indets' v0) ++ indets' v1
indets' (v0 :^: v1) = indets' v0 ++ indets' v1
indets' (v0 :*: v1) = indets' v0 ++ indets' v1
indets' (v0 :+: v1) = indets' v0 ++ indets' v1
indets' (v0 :/: v1) = indets' v0 ++ indets' v1
maskVariables :: Formula -- ^ Original formula which is not masked
-> Formula -- ^ Not masked variable
-> (Formula, (Formula -> Formula)) -- ^ (masked formula, reverse function)
maskVariables f x =
let vs = filter ((/=) x) $ variables f
toCV (V v) = (CV v)
toCV a = a
toV (CV v) = (V v)
toV a = a
v2cv = zip vs (map toCV vs)
cv2v = zip (map toCV vs) (map toV vs)
f' = subst v2cv f
in (f',subst cv2v)
| Greatest common divisor of the coefficients of formula with respect to variable of second function - args
--
-- >>> let [x,y] = map V ["x","y"]
-- >>> content (-4*x*y+6*y^2) x
( ( -4)*y , x + ( 3/-2)*y )
content :: Formula -- ^ formula
-> Formula -- ^ variable
-> (Formula,Formula) -- ^ (gcd-result,formula/gcd-result)
content f x =
let (f',rev) = maskVariables (expand f) x
(c,_) = headV f'
gcdr = gcdPolynomial f (rev c)
in (gcdr,f `quot` gcdr)
| null | https://raw.githubusercontent.com/junjihashimoto/th-cas/8fa179cf39c72c14dda4d77d824d31b32ad86dc0/Algebra/CAS/Base.hs | haskell | #LANGUAGE OverloadedStrings#
| Mathematical constant expression
^ Integer
^ Real Number
| Mathematical expression
^ Constant value
^ Pi
^ Imaginary Number
^ Constant variable which is used to deal variable(V Name) as constant value
^ Variable
^ Special Functions (sin, cos, exp and etc..)
| try simplification for multiply
>>> let [x,y] = map V ["x","y"]
>>> tryMul (x**(-1)) x
Just 1
| Lift String to variable of Formula
| Lift String to constant of Formula
| try to reduce a variable.
>>> let [a,b,c] = map CV ["a","b","c"]
>>> let [x,y,z] = map V ["x","y","z"]
>>> f0*f1
(1 + x + (-2)*y)*(4 + 2*x + 4*y)
4 + 6*x + 2*(x^2) + (-4)*y + (-8)*(y^2)
>>> expand $ (a*x-2*b*y+c)
c + a*x + (-2)*b*y
>>> expand $ - ((-2*b)/(4*b))
(-1)*(((-2)*b)/(4*b))
>>> expand $ - ((-2*b)/(4*b))*(2*a*x+4*b*y+4*c)
(-4)*(((-2)*b)/(4*b))*c + (-2)*a*(((-2)*b)/(4*b))*x + (-4)*(((-2)*b)/(4*b))*b*y
>>> expand $ (a*x-2*b*y+c) - ((-2*b)/(4*b))*(2*a*x+4*b*y+4*c)
c + (-4)*c*(((-2)*b)/(4*b)) + a*x + (-2)*(((-2)*b)/(4*b))*a*x + (-4)*b*(((-2)*b)/(4*b))*y + (-2)*b*y
^ a number of repetition of expanding formula
^ original formula
^ expanded formula
| substitute expression
>>> let [x,y,z] = map V ["x","y","z"]
>>> subst [(x,3),(y,5)] $ x+y
>>> subst [(tan(x),z)] (tan(x)**2+1)
^ List of tuple(orignal term, new term)
^ original formula
^ replaced formula
| When formula does not include variable,
isConst returns True.
>>> let x = "x" :: Formula
>>> isConst x
False
>>> isConst $ sin(x)*3
False
True
^ formula
| Find indeterminates of an expression
>>> let [x,y,z] = map V ["x","y","z"]
>>> indets (x*y+z/x)
[x,y,z]
[x,y]
>>> indets (sin(x)*cos(x)**2)
^ Original formula which is not masked
^ Not masked variable
^ (masked formula, reverse function)
>>> let [x,y] = map V ["x","y"]
>>> content (-4*x*y+6*y^2) x
^ formula
^ variable
^ (gcd-result,formula/gcd-result) |
module Algebra.CAS.Base where
import Data.String
import Data.List(nub)
data Const =
^ Zero
^ One
^ Faction = CF numer denom
deriving (Eq,Show,Read)
instance Ord Const where
compare Zero Zero = EQ
compare Zero One = LT
compare Zero (CI a) = compare 0 a
compare Zero (CF a b) = compare 0 (a*b)
compare Zero (CR a) = compare 0 a
compare One One = EQ
compare One (CI a) = compare 1 a
compare One (CF a b) = compare 1 (a*b)
compare One (CR a) = compare 1 a
compare (CI a) (CI b) = compare a b
compare (CI a) (CF b c) =
let v = fromIntegral b / fromIntegral c :: Double
in compare (fromIntegral a) v
compare (CI a) (CR b) = compare (fromIntegral a) b
compare (CF a b) (CF c d) =
let v0 = fromIntegral a / fromIntegral b :: Double
v1 = fromIntegral c / fromIntegral d :: Double
in compare v0 v1
compare (CF a b) (CR c) = compare (fromIntegral a / fromIntegral b) c
compare (CR a) (CR b) = compare a b
compare a b =
case compare b a of
LT -> GT
GT -> LT
EQ -> EQ
neg :: Const
neg = CI (-1)
constSimplify :: Const -> Const
constSimplify (CI 0) = Zero
constSimplify (CI 1) = One
constSimplify (CF 0 _) = Zero
constSimplify (CF a 1) = (CI a)
constSimplify (CF a (-1)) = (CI (-a))
constSimplify (CF a b) | a == b = One
| otherwise =
case gcd a b of
1 -> CF a b
g -> constSimplify $ CF (a`div`g) (b`div`g)
constSimplify (CR 0) = Zero
constSimplify (CR 1) = One
constSimplify a = a
instance Num Const where
fromInteger 0 = Zero
fromInteger 1 = One
fromInteger a = CI (fromIntegral a)
(+) a'' b'' =
case (a'',b'') of
(Zero,Zero) -> Zero
(Zero,b) -> b
(One,One) -> CI 2
(One,CI b') -> constSimplify $ CI (1+b')
(One,CF a' b') -> constSimplify $ CF (a'+b') b'
(One,CR b') -> constSimplify $ CR (1+b')
(CI a',CI b') -> constSimplify $ CI (a'+b')
(CI a',CF b' c') -> constSimplify $ CF (b'+c'*a') c'
(CI a',CR b') -> constSimplify $ CR ((fromIntegral a')+b')
(CF a' b',CF c' d') -> constSimplify $ CF (a'*d'+b'*c') (b'*d')
(CF a' b',CR c') -> constSimplify $ CR ((fromIntegral a')/(fromIntegral b')+c')
(CR a',CR b') -> constSimplify $ CR (a'+b')
(a,b) -> (+) b a
(-) a b | a == b = Zero
| otherwise = a + (neg * b)
(*) a'' b'' =
case (a'',b'') of
(Zero,Zero) -> Zero
(Zero,_) -> Zero
(One,One) -> One
(One,a') -> a'
(CI a',CI b') -> constSimplify $ CI (a'*b')
(CI a',CF b' c') -> constSimplify $ CF (b'*a') c'
(CI a',CR b') -> constSimplify $ CR ((fromIntegral a')*b')
(CF a' b',CF c' d') -> constSimplify $ CF (a'*c') (b'*d')
(CF a' b',CR c') -> constSimplify $ CR (fromIntegral a' * c' / fromIntegral b')
(CR a',CR b') -> constSimplify $ CR (a'*b')
(_,Zero) -> Zero
(a',One) -> a'
(a,b) -> (*) b a
abs Zero = Zero
abs One = One
abs (CI a) = CI (abs a)
abs (CF a b) = CF (abs a) (abs b)
abs (CR a) = CR (abs a)
signum Zero = CI 0
signum One = CI (-1)
signum (CI a) = CI (signum a)
signum (CF a b) = CI $ signum a * signum b
signum (CR a) = CI $ round $ signum a
instance Fractional Const where
fromRational 0 = Zero
fromRational 1 = One
fromRational a = CR (fromRational a)
recip a = (/) One a
(/) a' b' =
case (a',b') of
(Zero,_) -> Zero
(_,Zero) -> error "DivideByZero"
(One,One) -> One
(One,CI (-1)) -> CI (-1)
(One,CI a) -> CF 1 a
(One,CF a b) -> CF b a
(One,CR a) -> CR (1/a)
(CI a,CI (-1)) -> CI (-a)
(CI a,CI b) -> constSimplify $ CF a b
(CI a,CF b c) -> constSimplify $ CF (a*c) b
(CI a,CR b) -> constSimplify $ CR (fromIntegral a /b)
(CF a b,CF c d) -> constSimplify $ CF (a*d) (b*c)
(CF a b,CR c) -> constSimplify $ CR (fromIntegral a /fromIntegral b * c)
(CR a,CR b) -> constSimplify $ CR (a/b)
(a,One) -> a
(a,CI (-1)) -> -a
(CF b c,CI a) -> constSimplify $ CF b (a*c)
(CR b,CI a) -> constSimplify $ CR (b/fromIntegral a)
(CR c,CF a b) -> constSimplify $ CR (fromIntegral b /fromIntegral a * c)
instance Enum Const where
succ a = a+1
pred a = a-1
toEnum v = fromIntegral v
fromEnum Zero = 0
fromEnum One = 1
fromEnum (CI a) = fromEnum a
fromEnum (CR a) = fromEnum a
fromEnum (CF a b) = fromEnum ((fromIntegral a::Double) / fromIntegral b)
instance Real Const where
toRational Zero = toRational (0::Int)
toRational One = toRational (1::Int)
toRational (CI v) = toRational v
toRational (CR v) = toRational v
toRational (CF a b) = toRational ((fromIntegral a :: Double) / fromIntegral b)
instance Floating Const where
pi = CR pi
exp Zero = 1
exp a = CR $ exp $ fromRational $ toRational a
sqrt (CI a) | a2 == a = CI a1
| otherwise = CR $ sqrt $ fromRational $ toRational a
where
a0 = sqrt (fromIntegral a) :: Double
a1 = round a0 :: Integer
a2 = a1 * a1
sqrt a = CR $ sqrt $ fromRational $ toRational a
log One = Zero
log a = CR $ log $ fromRational $ toRational a
(**) _ Zero = 1
(**) a One = a
(**) a (CI b) = a^b
(**) a b = CR $ (fromRational $ toRational a :: Double) ** (fromRational $ toRational b :: Double)
logBase a b = CR $ logBase (fromRational $ toRational $ a) (fromRational $ toRational $ b)
sin a = CR $ sin $ fromRational $ toRational a
tan a = CR $ tan $ fromRational $ toRational a
cos a = CR $ cos $ fromRational $ toRational a
asin a = CR $ asin $ fromRational $ toRational a
atan a = CR $ atan $ fromRational $ toRational a
acos a = CR $ acos $ fromRational $ toRational a
sinh a = CR $ sinh $ fromRational $ toRational a
tanh a = CR $ tanh $ fromRational $ toRational a
cosh a = CR $ cosh $ fromRational $ toRational a
asinh a = CR $ asinh $ fromRational $ toRational a
atanh a = CR $ atanh $ fromRational $ toRational a
acosh a = CR $ acosh $ fromRational $ toRational a
toInt :: Const -> Maybe Integer
toInt Zero = Just 0
toInt One = Just 1
toInt (CI a) = Just a
toInt _ = Nothing
mapTuple :: (a -> b) -> (a,a) -> (b,b)
mapTuple f (a,b) = (f a, f b)
instance Integral Const where
quot a b = fst $ quotRem a b
rem a b = snd $ quotRem a b
quotRem a b =
case (toInt a,toInt b) of
(Just a',Just b') -> mapTuple (constSimplify.CI) $ quotRem a' b'
_ -> if a == b then (1,0) else (0,a)
div = quot
mod = rem
toInteger Zero = 0
toInteger One = 1
toInteger (CI a) = toInteger a
toInteger a = error $ "can not do toInteger:" ++ show a
data SpecialFunction =
Sin Formula
| Cos Formula
| Tan Formula
| Sinh Formula
| Cosh Formula
| Tanh Formula
| Asin Formula
| Acos Formula
| Atan Formula
| Asinh Formula
| Acosh Formula
| Atanh Formula
| Exp Formula
| Log Formula
| Abs Formula
| Sig Formula
| LogBase Formula Formula
| Sqrt Formula
| Diff Formula Formula
| Integrate Formula Formula
deriving (Show,Read,Eq,Ord)
data Formula =
| Formula :^: Formula
| Formula :*: Formula
| Formula :+: Formula
| Formula :/: Formula
deriving (Eq,Read)
(=:) :: Formula -> Formula -> Formula
(=:) a b = a - b
infix 0 =:
instance Ord Formula where
compare (C a) (C b) = compare a b
compare (C _) Pi = LT
compare (C _) I = LT
compare (C _) (CV _) = LT
compare (C _) _ = LT
compare Pi (C _) = GT
compare Pi Pi = EQ
compare Pi I = LT
compare Pi (CV _) = LT
compare Pi _ = LT
compare I (C _) = GT
compare I Pi = GT
compare I I = EQ
compare I (CV _) = LT
compare I _ = LT
compare (CV _) (C _) = GT
compare (CV _) Pi = GT
compare (CV _) I = GT
compare (CV a) (CV b) = compare a b
compare (CV _) _ = LT
compare (V a) (V b) = compare a b
compare (V _) b@(S _) | isConst b = GT
| otherwise = LT
compare a@(V _) (c@(V _):^:d) | a == c = compare 1 d
| otherwise = compare a c
compare (V _) b | isConst b = GT
| otherwise = LT
compare (S a) (S b) = compare a b
compare (a :*: b) (c :*: d) | b == d = compare a c
| otherwise = compare b d
compare (_ :*: b) c | b == c = GT
| otherwise = compare b c
compare a (_ :*: c) | a == c = LT
| otherwise = compare a c
compare (a :^: b) (c :^: d) | a == c = compare b d
| otherwise = compare a c
compare (a :^: b) c | a == c = compare b 1
| otherwise = compare a c
compare a (b :^: c) | a == b = compare 1 c
| otherwise = compare a b
compare (a :+: b) (c :+: d) | b == d = compare a c
| otherwise = compare b d
compare (_ :+: b) c | b == c = GT
| otherwise = compare b c
compare a (b :+: c) | a == c = LT
| otherwise = compare b c
compare (a :/: b) (c :/: d) = compare (a*d) (c*b)
compare (_ :/: b) c = compare b (c*b)
compare a (b :/: c) = compare (a*c) b
compare a b =
case (isConst a,isConst b) of
(True,True) -> EQ
(True,False) -> LT
(False,True) -> GT
(False,False) ->
case compare b a of
LT -> GT
GT -> LT
EQ -> EQ
tryPlus :: Formula -> Formula -> Maybe Formula
tryPlus (C Zero) (C Zero) = Just (C Zero)
tryPlus (C Zero) a = Just a
tryPlus a (C Zero) = Just a
tryPlus (C a) (C b) = Just $ C (a+b)
tryPlus I I = Just $ C (CI 2) :*: I
tryPlus a@(V _) b@(V _) | a == b = Just $ C (CI 2) :*: a
| otherwise = Nothing
tryPlus a@(V _:^: _) b@(V _:^: _) | a == b = Just $ C (CI 2) :*: a
| otherwise = Nothing
tryPlus (a:+:b) c =
case tryPlus b c of
Nothing ->
case tryPlus a c of
Nothing -> Nothing
Just v -> Just $ v + b
Just v -> Just $ a + v
tryPlus (a:*:b) (c:*:d) =
if b == d then
case tryPlus a c of
Nothing -> Nothing
Just v -> Just $ v * b
else
Nothing
tryPlus (a:*:b) d =
if b == d then
case tryPlus a (C One) of
Nothing -> Nothing
Just v -> Just $ v * b
else
Nothing
tryPlus a (c:*:d) =
if a == d then
case tryPlus (C One) c of
Nothing -> Nothing
Just v -> Just $ v * a
else
Nothing
tryPlus _ _ = Nothing
insertPlus :: Formula -> Formula -> Formula
insertPlus a'@(a:+:b) v | v <= b = insertPlus a v :+: b
| otherwise = a':+:v
insertPlus a v | a <= v = a :+: v
| otherwise = v :+: a
tryMul :: Formula -> Formula -> Maybe Formula
tryMul I I = Just $ C neg
tryMul (C Zero) _ = Just $ C Zero
tryMul _ (C Zero) = Just $ C Zero
tryMul (C One) a = Just a
tryMul a (C One) = Just a
tryMul (C a) (C b) = Just $ C (a*b)
tryMul a@(V _) b@(V _) | a == b = Just $ a :^: C (CI 2)
| otherwise = Nothing
tryMul (a@(V _):^: b) (c@(V _):^:d) | a == c = Just $ if b+d==0 then 1 else a :^: (b+d)
| otherwise = Nothing
tryMul a@(V _) (c@(V _):^:d) | a == c = Just $ if 1+d == 0 then 1 else a :^: (1+d)
| otherwise = Nothing
tryMul (a@(V _):^: b) c@(V _) | a == c = Just $ if b+1 == 0 then 1 else a :^: (b+1)
| otherwise = Nothing
tryMul (a@(V _):/: b) c | b == c = Just a
| otherwise = Nothing
tryMul (a:*:b) c =
case tryMul b c of
Nothing ->
case tryMul a c of
Nothing -> Nothing
Just v -> Just $ v * b
Just v -> Just $ a * v
tryMul _ _ = Nothing
insertMul :: Formula -> Formula -> Formula
insertMul a'@(a:*:b) v | v <= b = insertMul a v :*: b
| otherwise = a':*:v
insertMul a v | a <= v = a :*: v
| otherwise = v :*: a
constDiv :: Formula -> Formula -> Formula
constDiv a'' b'' =
case (a'',b'') of
(C a',C b') -> C (a'/b')
(C Zero,_) -> C Zero
(_,C Zero) -> error "divide by zero"
(C One,b) -> C One :/: b
(a,C One) -> a
(a,C c) -> C (1/c) * a
(a,b) | a == b -> C One
| otherwise -> a :/: b
splitExp :: Formula -> (Formula,Formula)
splitExp (a:^:b) = (a,b)
splitExp a = (a,1)
divGB :: Formula -> Formula -> Formula
divGB a b = conv $ (ca `constDiv` cb) * divGB' va vb
where
(ca,va) = head' a
(cb,vb) = head' b
head' :: Formula -> (Formula,Formula)
head' v' = var (firstTerm,1)
where
firstTerm = v'
var (c,v) =
if isConst c
then (c,v)
else var (tailMul c,headMul c*v)
conv (a':*:(C One :/: c)) = a':/:c
conv a' = a'
divGB' :: Formula -> Formula -> Formula
divGB' 1 1 = 1
divGB' a 1 = a
divGB' 1 a = 1 `constDiv` a
divGB' a b =
if hva == hvb
then divGB' ta tb * (hva ** (hpa- hpb))
else if hva < hvb
then divGB' a tb `constDiv` (hvb ** hpb)
else divGB' ta b * (hva ** hpa)
where
(hva,hpa) = splitExp $ headMul a
(hvb,hpb) = splitExp $ headMul b
ta = tailMul a
tb = tailMul b
divAll :: Formula -> Formula -> Formula
divAll a b = expand $ t + (h/b)
where
h = headAdd a
t = case (tailAdd a) of
0 -> 0
v -> divAll v b
instance Num Formula where
fromInteger 0 = C Zero
fromInteger 1 = C One
fromInteger a = C $ CI (fromIntegral a)
(+) a (b:+:c) =
case tryPlus a c of
Just v -> v + b
Nothing -> insertPlus a c + b
(+) a b =
case tryPlus a b of
Just v -> v
Nothing -> insertPlus a b
(-) a b | a == b = C Zero
| otherwise = a + (b * (C neg))
(*) a (b:*:c) =
case tryMul a c of
Just v -> v * b
Nothing -> insertMul a c * b
(*) a b =
case tryMul a b of
Just v -> v
Nothing -> insertMul a b
abs a = S (Abs a)
signum a = S (Sig a)
instance Fractional Formula where
fromRational 0 = C Zero
fromRational 1 = C One
fromRational a = C $ CR (fromRational a)
recip a = (/) (C One) a
(/) a b = divGB a b
instance Floating Formula where
pi = Pi
exp (C Zero) = C One
exp a = S $ Exp a
sqrt (C Zero) = 0
sqrt (C One) = 1
sqrt a'@(C (CI a)) | a < 0 = I * sqrt (-a')
| a2 == a = C $ CI a1
| otherwise = S $ Sqrt a'
where
a0 = sqrt (fromIntegral a) :: Double
a1 = round a0 :: Integer
a2 = a1 * a1
sqrt a = S $ Sqrt a
log (C One) = C Zero
log a = S $ Log a
(**) _ (C Zero) = C One
(**) (C (CI a)) (C (CI b)) = C (CI (a^b))
(**) a (C One) = a
(**) a b = (:^:) a b
logBase a b = S $ LogBase a b
sin = S . Sin
tan = S . Tan
cos = S . Cos
asin = S . Asin
atan = S . Atan
acos = S . Acos
sinh = S . Sinh
tanh = S . Tanh
cosh = S . Cosh
asinh = S . Asinh
atanh = S . Atanh
acosh = S . Acosh
instance IsString Formula where
fromString = val
val :: String -> Formula
val v = V v
cval :: String -> Formula
cval v = CV v
instance Enum Formula where
succ a = a+1
pred a = a-1
toEnum v = fromIntegral v
fromEnum (C Zero) = 0
fromEnum (C One) = 1
fromEnum (C (CI a)) = fromIntegral a
fromEnum a = error $ "can not do fromEnum:" ++ show a
instance Real Formula where
toRational (C (CI v)) = toRational v
toRational (C (CR v)) = toRational v
toRational Pi = toRational (pi::Double)
toRational (C Zero) = toRational (0::Int)
toRational (C One) = toRational (1::Int)
toRational _ = toRational (0::Int)
lcmMonomial :: Formula -> Formula -> Formula
lcmMonomial a b = lcmV ca cb * lcmMonomial' va vb
where
(ca,va) = headV a
(cb,vb) = headV b
lcmV :: Formula -> Formula -> Formula
lcmV (C a') (C b') = C (lcm a' b')
lcmV a' b' = a' * b'
lcmMonomial' :: Formula -> Formula -> Formula
lcmMonomial' 1 1 = 1
lcmMonomial' a 1 = a
lcmMonomial' 1 a = a
lcmMonomial' a b =
if hva == hvb
then lcmMonomial' ta tb * (hva ** max hpa hpb)
else if hva < hvb
then lcmMonomial' a tb * (hvb ** hpb)
else lcmMonomial' ta b * (hva ** hpa)
where
(hva,hpa) = splitExp $ headMul a
(hvb,hpb) = splitExp $ headMul b
ta = tailMul a
tb = tailMul b
reduction :: Formula -> Formula -> (Formula,Formula)
reduction f g =
if va == vl
then
if va == 1
then (ca/cb,0)
else
let (a,b) = reduction (expand (f - c*g)) g
in (c+a,b)
else
case mt of
0 -> (0,h)
t -> let (a,b) = reduction t g
in (a,b+h)
where
(ca,va) = headV f
(cb,vb) = headV g
lcm' = lcmMonomial va vb
(cl,vl) = headV lcm'
h = headAdd f
mt = tailAdd f
c = (lcm' / vb)*ca/cb
reductions :: Formula -> [Formula] -> Formula
reductions f [] = f
reductions f (g:gs) =
let (_,b) = reduction f g
in case b of
0 -> 0
c -> expand $ reductions (expand c) gs
instance Integral Formula where
quot a b = fst $ quotRem a b
rem a b = snd $ quotRem a b
quotRem = reduction
div = quot
mod = rem
toInteger (C Zero) = 0
toInteger (C One) = 1
toInteger (C (CI a)) = toInteger a
toInteger a = error $ "can not do toInteger:" ++ show a
degree :: Formula -> Formula
degree (C _) = 0
degree (CV _) = 0
degree (V _) = 1
degree (S (Sin v)) = degree v
degree (S (Cos v)) = degree v
degree (S (Tan v)) = degree v
degree (S (Sinh v)) = degree v
degree (S (Cosh v)) = degree v
degree (S (Tanh v)) = degree v
degree (S (Asin v)) = degree v
degree (S (Acos v)) = degree v
degree (S (Atan v)) = degree v
degree (S (Asinh v)) = degree v
degree (S (Acosh v)) = degree v
degree (S (Atanh v)) = degree v
degree (S (Exp v)) = degree v
degree (S (Log v)) = degree v
degree (S (Abs v)) = degree v
degree (S (Sig v)) = degree v
degree (S (LogBase v0 v1)) = max (degree v0) (degree v1)
degree Pi = 0
degree I = 0
degree (S (Sqrt v)) = degree v
degree (S (Diff v0 v1)) = max (degree v0) (degree v1)
degree (S (Integrate v0 v1)) = max (degree v0) (degree v1)
degree (v0 :^: v1) = v1 * degree v0
degree (v0 :*: v1) = max (degree v0) (degree v1)
degree (v0 :+: v1) = max (degree v0) (degree v1)
degree (v0 :/: v1) = max (degree v0) (degree v1)
converge :: (Formula -> Formula) -> Formula -> Formula
converge func v =
let v' = func v
in if v' == v
then v'
else converge func v'
> > > let [ f0,f1 ] = [ ( 2*x+4*y+4),(x-2*y+1 ) ]
> > > expand $ f0*f1
expand :: Formula -> Formula
expand f = expand' 100 f
expand' d f | d <= 0 = f
| otherwise =
case f of
((a:+:b):*:c) -> let (a',b',c') = (expand' (d-1) a,expand' (d-1) b,expand' (d-1) c) in expand' (d-1) (a'*c') + expand' (d-1) (b'*c')
(a:*:(b:+:c)) -> let (a',b',c') = (expand' (d-1) a,expand' (d-1) b,expand' (d-1) c) in expand' (d-1) (a'*b') + expand' (d-1) (a'*c')
(a:+:b) -> let (a',b') = (expand' (d-1) a,expand' (d-1) b) in a'+b'
c@(a:*:b) -> let (a',b') = (expand' (d-1) a,expand' (d-1) b)
c' = a'*b'
in if c==c' then c' else expand' (d-1) c'
(a:/:1) -> expand' (d-1) a
a -> a
expandIO :: Formula -> IO Formula
expandIO f = do
print f
case f of
((a:+:b):*:c) -> do
print "((a:+:b):*:c)"
print a
print b
print c
a' <- expandIO a
b' <- expandIO b
c' <- expandIO c
ac <- expandIO (a'*c')
bc <- expandIO (b'*c')
return $ ac + bc
(a:*:(b:+:c)) -> do
print "(a:*:(b:+:c))"
print a
print b
print c
a' <- expandIO a
b' <- expandIO b
c' <- expandIO c
ab <- expandIO (a'*b')
ac <- expandIO (a'*c')
return $ ab + ac
(a:+:b) -> do
print "(a:+:b)"
print a
print b
a' <- expandIO a
b' <- expandIO b
return $ a'+b'
c@(a:*:b) -> do
print "(a:*:b)"
print a
print b
a' <- expandIO a
b' <- expandIO b
let c' = a'*b'
if c==c' then return c' else expandIO c'
(a:/:1) -> return $ expand a
a -> return a
gcdPolynomial :: Formula -> Formula -> Formula
gcdPolynomial a b | a == 0 = b
| b == 0 = a
| otherwise =
let (a',b') = if a>=b then (a,b) else (b,a)
r = a' `rem` b'
in case r of
0 -> b'
_ -> if r == a' then 1 else gcdPolynomial r b'
lcmPolynomial :: Formula -> Formula -> Formula
lcmPolynomial a b =
let g = gcdPolynomial a b
d0 = a `div` g
d1 = b `div` g
in expand $ d0*d1*g
headAdd :: Formula -> Formula
headAdd (_ :+: ab) = ab
headAdd ab = ab
tailAdd :: Formula -> Formula
tailAdd (a :+: _) = a
tailAdd _ = 0
mapAdd :: (Formula -> Formula) -> Formula -> Formula
mapAdd func formula =
case t of
0 -> func h
_ -> mapAdd func t + func h
where
h = headAdd formula
t = tailAdd formula
splitAdd :: Formula -> [Formula]
splitAdd formula =
case t of
0 -> [h]
_ -> h : splitAdd t
where
h = headAdd formula
t = tailAdd formula
headMul :: Formula -> Formula
headMul (_ :*: ab) = ab
headMul ab = ab
tailMul :: Formula -> Formula
tailMul (a :*: _) = a
tailMul _ = 1
headDiv :: Formula -> Formula
headDiv (_ :/: ab) = ab
headDiv ab = ab
tailDiv :: Formula -> Maybe Formula
tailDiv (a :/: _) = Just a
tailDiv _ = Nothing
8
1 + z^2
subst [] formula = formula
subst ((org,mod'):other) formula = subst other $ subst' org mod' formula
subst' :: Formula -> Formula -> Formula -> Formula
subst' org new formula =
if org == formula
then new
else case formula of
a@(C _) -> a
a@(CV _) -> a
a@Pi -> a
a@I -> a
a@(V _) -> a
(S (Sin v)) -> S $ Sin $ subst' org new v
(S (Cos v)) -> S $ Cos $ subst' org new v
(S (Tan v)) -> S $ Tan $ subst' org new v
(S (Sinh v)) -> S $ Sinh $ subst' org new v
(S (Cosh v)) -> S $ Cosh $ subst' org new v
(S (Tanh v)) -> S $ Tanh $ subst' org new v
(S (Asin v)) -> S $ Asin $ subst' org new v
(S (Acos v)) -> S $ Acos $ subst' org new v
(S (Atan v)) -> S $ Atan $ subst' org new v
(S (Asinh v)) -> S $ Asinh $ subst' org new v
(S (Acosh v)) -> S $ Acosh $ subst' org new v
(S (Atanh v)) -> S $ Atanh $ subst' org new v
(S (Exp v)) -> S $ Exp $ subst' org new v
(S (Log v)) -> S $ Log $ subst' org new v
(S (Abs v)) -> S $ Abs $ subst' org new v
(S (Sig v)) -> S $ Sig $ subst' org new v
(S (LogBase v1 v2)) -> S $ LogBase (subst' org new v1) (subst' org new v2)
(S (Sqrt v)) -> S $ Sqrt $ subst' org new v
(S (Diff v1 v2)) -> S $ Diff (subst' org new v1) (subst' org new v2)
(S (Integrate v1 v2)) -> S $ Integrate (subst' org new v1) (subst' org new v2)
(a:^:b) -> subst' org new a ** subst' org new b
(a:*:b) -> subst' org new a * subst' org new b
(a:+:b) -> subst' org new a + subst' org new b
(a:/:b) -> subst' org new a / subst' org new b
mapFormula :: (Formula -> Formula) -> Formula -> Formula
mapFormula conv a@(C _) = conv a
mapFormula conv a@(CV _) = conv a
mapFormula conv a@Pi = conv a
mapFormula conv a@I = conv a
mapFormula conv a@(V _) = conv a
mapFormula conv (S (Sin v)) = S $ Sin $ mapFormula conv v
mapFormula conv (S (Cos v)) = S $ Cos $ mapFormula conv v
mapFormula conv (S (Tan v)) = S $ Tan $ mapFormula conv v
mapFormula conv (S (Sinh v)) = S $ Sinh $ mapFormula conv v
mapFormula conv (S (Cosh v)) = S $ Cosh $ mapFormula conv v
mapFormula conv (S (Tanh v)) = S $ Tanh $ mapFormula conv v
mapFormula conv (S (Asin v)) = S $ Asin $ mapFormula conv v
mapFormula conv (S (Acos v)) = S $ Acos $ mapFormula conv v
mapFormula conv (S (Atan v)) = S $ Atan $ mapFormula conv v
mapFormula conv (S (Asinh v)) = S $ Asinh $ mapFormula conv v
mapFormula conv (S (Acosh v)) = S $ Acosh $ mapFormula conv v
mapFormula conv (S (Atanh v)) = S $ Atanh $ mapFormula conv v
mapFormula conv (S (Exp v)) = S $ Exp $ mapFormula conv v
mapFormula conv (S (Log v)) = S $ Log $ mapFormula conv v
mapFormula conv (S (Abs v)) = S $ Abs $ mapFormula conv v
mapFormula conv (S (Sig v)) = S $ Sig $ mapFormula conv v
mapFormula conv (S (LogBase v1 v2)) = S $ LogBase (mapFormula conv v1) (mapFormula conv v2)
mapFormula conv (S (Sqrt v)) = S $ Sqrt $ mapFormula conv v
mapFormula conv (S (Diff v1 v2)) = S $ Diff (mapFormula conv v1) (mapFormula conv v2)
mapFormula conv (S (Integrate v1 v2)) = S $ Integrate (mapFormula conv v1) (mapFormula conv v2)
mapFormula conv (a:^:b) = mapFormula conv a ** mapFormula conv b
mapFormula conv (a:*:b) = mapFormula conv a * mapFormula conv b
mapFormula conv (a:+:b) = mapFormula conv a + mapFormula conv b
mapFormula conv (a:/:b) = mapFormula conv a / mapFormula conv b
> > > isConst $ 3.0 * sin(3.0 )
isConst :: Formula -> Bool
isConst (C _) = True
isConst (CV _) = True
isConst (V _) = False
isConst (S (Sin v)) = isConst v
isConst (S (Cos v)) = isConst v
isConst (S (Tan v)) = isConst v
isConst (S (Sinh v)) = isConst v
isConst (S (Cosh v)) = isConst v
isConst (S (Tanh v)) = isConst v
isConst (S (Asin v)) = isConst v
isConst (S (Acos v)) = isConst v
isConst (S (Atan v)) = isConst v
isConst (S (Asinh v)) = isConst v
isConst (S (Acosh v)) = isConst v
isConst (S (Atanh v)) = isConst v
isConst (S (Exp v)) = isConst v
isConst (S (Log v)) = isConst v
isConst (S (Abs v)) = isConst v
isConst (S (Sig v)) = isConst v
isConst (S (LogBase v0 v1)) = isConst v0 && isConst v1
isConst Pi = True
isConst I = True
isConst (S (Sqrt v)) = isConst v
isConst (S (Diff v0 v1)) = isConst v0 && isConst v1
isConst (S (Integrate v0 v1)) = isConst v0 && isConst v1
isConst (v0 :^: v1) = isConst v0 && isConst v1
isConst (v0 :*: v1) = isConst v0 && isConst v1
isConst (v0 :+: v1) = isConst v0 && isConst v1
isConst (v0 :/: v1) = isConst v0 && isConst v1
hasVariable :: Formula -> Formula -> Bool
hasVariable f v = elem v $ variables f
isVariable :: Formula -> Bool
isVariable = not.isConst
variables :: Formula -> [Formula]
variables (C _) = []
variables (CV _) = []
variables a@(V _) = [a]
variables (S (Sin v)) = variables v
variables (S (Cos v)) = variables v
variables (S (Tan v)) = variables v
variables (S (Sinh v)) = variables v
variables (S (Cosh v)) = variables v
variables (S (Tanh v)) = variables v
variables (S (Asin v)) = variables v
variables (S (Acos v)) = variables v
variables (S (Atan v)) = variables v
variables (S (Asinh v)) = variables v
variables (S (Acosh v)) = variables v
variables (S (Atanh v)) = variables v
variables (S (Exp v)) = variables v
variables (S (Log v)) = variables v
variables (S (Abs v)) = variables v
variables (S (Sig v)) = variables v
variables (S (LogBase v0 v1)) = variables v0 ++ variables v1
variables Pi = []
variables I = []
variables (S (Sqrt v)) = variables v
variables (S (Diff v0 v1)) = variables v0 ++ variables v1
variables (S (Integrate v0 v1)) = variables v0 ++ variables v1
variables (v0 :^: v1) = variables v0 ++ variables v1
variables (v0 :*: v1) = variables v0 ++ variables v1
variables (v0 :+: v1) = variables v0 ++ variables v1
variables (v0 :/: v1) = variables v0 ++ variables v1
denom :: Formula -> Formula
denom (_ :*: (_:/:b)) = b
denom (_:/:b) = b
denom _ = 1
numer :: Formula -> Formula
numer (a :*: (b:/:_)) = a * b
numer (a:/:_) = a
numer a = a
^ ( coefficient of first term , variables of first term )
headV v' = var (firstTerm,1)
where
firstTerm = headAdd v'
var (c,v) =
if isConst c
then (c,v)
else var (tailMul c,headMul c*v)
| Pretty print for Formula type .
Formula 's show function is the same as this .
ppr :: Formula -> String
ppr (C Zero) = "0"
ppr (C One) = "1"
ppr (C (CI a)) = show a
ppr (C (CF a b)) = show a ++"/"++show b
ppr (C (CR a)) = show a
ppr Pi = "π"
ppr I = "i"
ppr (CV v) = v
ppr (V v) = v
ppr (S (Exp v)) = "e(" ++ ppr v ++")"
ppr (S (Log v)) = "log(" ++ ppr v ++")"
ppr (S (Sqrt v)) = "√(" ++ ppr v ++")"
ppr (S (Diff f x)) = "diff(" ++ ppr f ++","++ppr x++")"
ppr (S (Integrate f x)) ="integrate(" ++ ppr f ++","++ppr x++")"
ppr (S (LogBase a b)) = "log_" ++ ppr a++ "(" ++ppr b ++")"
ppr (S (Sig v)) = "sig(" ++ ppr v ++")"
ppr (S (Abs v)) = "|" ++ ppr v ++"|"
ppr (S (Sin v)) = "sin(" ++ ppr v ++")"
ppr (S (Cos v)) = "cos(" ++ ppr v ++")"
ppr (S (Tan v)) = "tan(" ++ ppr v ++")"
ppr (S (Sinh v)) = "sinh(" ++ ppr v ++")"
ppr (S (Cosh v)) = "cosh(" ++ ppr v ++")"
ppr (S (Tanh v)) = "tanh(" ++ ppr v ++")"
ppr (S (Asin v)) = "asin(" ++ ppr v ++")"
ppr (S (Acos v)) = "acos(" ++ ppr v ++")"
ppr (S (Atan v)) = "atan(" ++ ppr v ++")"
ppr (S (Asinh v)) = "asinh(" ++ ppr v ++")"
ppr (S (Acosh v)) = "acosh(" ++ ppr v ++")"
ppr (S (Atanh v)) = "atanh(" ++ ppr v ++")"
ppr (a:^:b) = ppr a ++"^"++ ppr b
ppr (a'@(_:*:_):*:c) = ppr a'++"*" ++ ppr' c
ppr (a:*:b) = ppr' a ++"*"++ ppr' b
ppr (a:+:b) = ppr a ++" + "++ ppr b
ppr (a:/:b) = "(" ++ ppr a ++")/("++ ppr b ++")"
ppr' :: Formula -> String
ppr' c@(C (CI _)) = if c >= 0 then ppr c else "(" ++ ppr c ++ ")"
ppr' c@(C (CR _)) = if c >= 0 then ppr c else "(" ++ ppr c ++ ")"
ppr' c@I = ppr c
ppr' c@Pi = ppr c
ppr' c@(V _) = ppr c
ppr' c@(CV _) = ppr c
ppr' c = "(" ++ ppr c ++ ")"
instance Show Formula where
show = ppr
| This print shows bare structure of Formula type .
This string can be read by Formula 's read function .
showFormula :: Formula -> String
showFormula (C a) = "C (" ++ show a ++")"
showFormula Pi = "Pi"
showFormula I = "I"
showFormula (CV v) = "CV \"" ++ v ++"\""
showFormula (V v) = "V \"" ++ v ++"\""
showFormula (S a) = "S (" ++ show a ++")"
showFormula (a:^:b) = "(" ++ showFormula a ++" :^: "++ showFormula b ++")"
showFormula (a:*:b) = "(" ++ showFormula a ++" :*: "++ showFormula b ++")"
showFormula (a:+:b) = "(" ++ showFormula a ++" :+: "++ showFormula b ++")"
showFormula (a:/:b) = "(" ++ showFormula a ++" :/: "++ showFormula b ++")"
genCoeff :: String -> Int -> [Formula]
genCoeff prefix a = genCoeff' prefix a
where
len = fromIntegral (round (logBase 10 (fromIntegral a))) :: Int
nstr n =
let str = show n
l = length str
in take (len-l) (repeat '0') ++ str
genCoeff' prefix' a' | a' <=0 = []
| otherwise = CV (prefix' ++ nstr (pred a')) : genCoeff' prefix' (pred a')
genVars :: String -> Int -> [Formula]
genVars prefix a = gen' prefix a
where
len = fromIntegral (round (logBase 10 (fromIntegral a))) :: Int
nstr n =
let str = show n
l = length str
in take (len-l) (repeat '0') ++ str
gen' prefix' a' | a' <=0 = []
| otherwise = V (prefix' ++ nstr (pred a')) : gen' prefix' (pred a')
> > > indets ( 3*x^2 - x*y - y^2 )
[ sin(x),x , cos(x ) ]
indets :: Formula -> [Formula]
indets = nub.indets'
indets' :: Formula -> [Formula]
indets' (C _) = []
indets' (CV _) = []
indets' a@(V _) = [a]
indets' a@(S (Sin v)) = a:indets' v
indets' a@(S (Cos v)) = a:indets' v
indets' a@(S (Tan v)) = a:indets' v
indets' a@(S (Sinh v)) = a:indets' v
indets' a@(S (Cosh v)) = a:indets' v
indets' a@(S (Tanh v)) = a:indets' v
indets' a@(S (Asin v)) = a:indets' v
indets' a@(S (Acos v)) = a:indets' v
indets' a@(S (Atan v)) = a:indets' v
indets' a@(S (Asinh v)) = a:indets' v
indets' a@(S (Acosh v)) = a:indets' v
indets' a@(S (Atanh v)) = a:indets' v
indets' a@(S (Exp v)) = a:indets' v
indets' a@(S (Log v)) = a:indets' v
indets' a@(S (Abs v)) = a:indets' v
indets' a@(S (Sig v)) = a:indets' v
indets' a@(S (LogBase v0 v1)) = a:indets' v0 ++ a:indets' v1
indets' Pi = []
indets' I = []
indets' a@(S (Sqrt v)) = a:indets' v
indets' a@(S (Diff v0 v1)) = (a:indets' v0) ++ indets' v1
indets' a@(S (Integrate v0 v1)) = (a:indets' v0) ++ indets' v1
indets' (v0 :^: v1) = indets' v0 ++ indets' v1
indets' (v0 :*: v1) = indets' v0 ++ indets' v1
indets' (v0 :+: v1) = indets' v0 ++ indets' v1
indets' (v0 :/: v1) = indets' v0 ++ indets' v1
maskVariables f x =
let vs = filter ((/=) x) $ variables f
toCV (V v) = (CV v)
toCV a = a
toV (CV v) = (V v)
toV a = a
v2cv = zip vs (map toCV vs)
cv2v = zip (map toCV vs) (map toV vs)
f' = subst v2cv f
in (f',subst cv2v)
| Greatest common divisor of the coefficients of formula with respect to variable of second function - args
( ( -4)*y , x + ( 3/-2)*y )
content f x =
let (f',rev) = maskVariables (expand f) x
(c,_) = headV f'
gcdr = gcdPolynomial f (rev c)
in (gcdr,f `quot` gcdr)
|
4b045de34dbf3c1bb87c5cabe217c27fe1187c50fab71e05ac82efef022c66d0 | juspay/atlas | Main.hs | |
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Module : Main
Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022
License : Apache 2.0 ( see the file LICENSE )
Maintainer :
Stability : experimental
Portability : non - portable
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Module : Main
Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022
License : Apache 2.0 (see the file LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Main where
import ParkingBppApp (runMockParkingBPP)
import Relude
main :: IO ()
main = runMockParkingBPP
| null | https://raw.githubusercontent.com/juspay/atlas/e64b227dc17887fb01c2554db21c08284d18a806/app/mock-parking-bpp/server/Main.hs | haskell | |
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Module : Main
Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022
License : Apache 2.0 ( see the file LICENSE )
Maintainer :
Stability : experimental
Portability : non - portable
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Module : Main
Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022
License : Apache 2.0 (see the file LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Main where
import ParkingBppApp (runMockParkingBPP)
import Relude
main :: IO ()
main = runMockParkingBPP
| |
883ff587042c698d950f010dd3c8766d39e47b26f644e56962d7b05e5b465993 | exercism/babashka | allergies_test.clj | (ns allergies-test
(:require [clojure.test :refer [deftest is]]
allergies))
(deftest no-allergies-at-all
(is (= [] (allergies/allergies 0))))
(deftest allergic-to-just-eggs
(is (= [:eggs] (allergies/allergies 1))))
(deftest allergic-to-just-peanuts
(is (= [:peanuts] (allergies/allergies 2))))
(deftest allergic-to-just-strawberries
(is (= [:strawberries] (allergies/allergies 8))))
(deftest allergic-to-eggs-and-peanuts
(is (= [:eggs :peanuts] (allergies/allergies 3))))
(deftest allergic-to-more-than-eggs-but-not-peanuts
(is (= [:eggs :shellfish] (allergies/allergies 5))))
(deftest allergic-to-lots-of-stuff
(is (= [:strawberries :tomatoes :chocolate :pollen :cats]
(allergies/allergies 248))))
(deftest allergic-to-everything
(is (= [:eggs :peanuts :shellfish :strawberries
:tomatoes :chocolate :pollen :cats]
(allergies/allergies 255))))
(deftest no-allergies-means-not-allergic-peanuts
(is (not (allergies/allergic-to? 0 :peanuts))))
(deftest no-allergies-means-not-allergic-cats
(is (not (allergies/allergic-to? 0 :cats))))
(deftest no-allergies-means-not-allergic-strawberries
(is (not (allergies/allergic-to? 0 :strawberries))))
(deftest is-allergic-to-eggs
(is (allergies/allergic-to? 1 :eggs)))
(deftest allergic-to-eggs-in-addition-to-other-stuff
(is (allergies/allergic-to? 5 :eggs)))
(deftest ignore-non-allergen-score-parts
(is (= [:eggs :shellfish :strawberries :tomatoes :chocolate :pollen :cats]
(allergies/allergies 509))))
| null | https://raw.githubusercontent.com/exercism/babashka/707356c52e08490e66cb1b2e63e4f4439d91cf08/exercises/practice/allergies/test/allergies_test.clj | clojure | (ns allergies-test
(:require [clojure.test :refer [deftest is]]
allergies))
(deftest no-allergies-at-all
(is (= [] (allergies/allergies 0))))
(deftest allergic-to-just-eggs
(is (= [:eggs] (allergies/allergies 1))))
(deftest allergic-to-just-peanuts
(is (= [:peanuts] (allergies/allergies 2))))
(deftest allergic-to-just-strawberries
(is (= [:strawberries] (allergies/allergies 8))))
(deftest allergic-to-eggs-and-peanuts
(is (= [:eggs :peanuts] (allergies/allergies 3))))
(deftest allergic-to-more-than-eggs-but-not-peanuts
(is (= [:eggs :shellfish] (allergies/allergies 5))))
(deftest allergic-to-lots-of-stuff
(is (= [:strawberries :tomatoes :chocolate :pollen :cats]
(allergies/allergies 248))))
(deftest allergic-to-everything
(is (= [:eggs :peanuts :shellfish :strawberries
:tomatoes :chocolate :pollen :cats]
(allergies/allergies 255))))
(deftest no-allergies-means-not-allergic-peanuts
(is (not (allergies/allergic-to? 0 :peanuts))))
(deftest no-allergies-means-not-allergic-cats
(is (not (allergies/allergic-to? 0 :cats))))
(deftest no-allergies-means-not-allergic-strawberries
(is (not (allergies/allergic-to? 0 :strawberries))))
(deftest is-allergic-to-eggs
(is (allergies/allergic-to? 1 :eggs)))
(deftest allergic-to-eggs-in-addition-to-other-stuff
(is (allergies/allergic-to? 5 :eggs)))
(deftest ignore-non-allergen-score-parts
(is (= [:eggs :shellfish :strawberries :tomatoes :chocolate :pollen :cats]
(allergies/allergies 509))))
| |
0420759e97052574f67bdcaa3dabb102442eda96742544902e2c9f291c6b3c5b | timothypratley/leaderboardx | devcards.cljs | (ns dev.devcards
(:require
[algopop.leaderboardx.app.views.common :as common]
[algopop.leaderboardx.app.views.assess :as assess]
[devcards.core :as dc :refer-macros [defcard]]
[reagent.core :as reagent]))
(enable-console-print!)
(defcard
"# Test")
| null | https://raw.githubusercontent.com/timothypratley/leaderboardx/ad1719b3bb49fb7ab495ed833f1a451ebb3aec4d/env/dev/cljs/dev/devcards.cljs | clojure | (ns dev.devcards
(:require
[algopop.leaderboardx.app.views.common :as common]
[algopop.leaderboardx.app.views.assess :as assess]
[devcards.core :as dc :refer-macros [defcard]]
[reagent.core :as reagent]))
(enable-console-print!)
(defcard
"# Test")
| |
d2e51cfad5e4cae5e44d4d058d6aee822453178fb4943f00353a27009632fa9a | RefactoringTools/HaRe | InfixIn3AST.hs | module InfixIn3 where
data Inf a b = Nil | a :* b
data Try = C1 Try2
data Try2 = C2 [Int]
data T = MkT [a]
f :: (Inf [Int] (Either Int Int)) -> [Int]
f Nil = []
f ((a :* b@(Left b_1))) = a
f ((a :* b@(Right b_1))) = a
f ((a :* b)) = a
h :: (Inf [Int] (Either Int Int)) -> [Int]
h Nil = []
h ((a@[] :* b)) = a
h ((a@((x : xs)) :* b)) = a
j :: Int -> Try -> [Int]
j v x@(C1 b_1@(C2 b_2)) = []
j v x@(C1 b_1) = []
j v x = []
p :: [a] -> a
p ((x : xs)) = x
| null | https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/old/testing/subIntroPattern/InfixIn3AST.hs | haskell | module InfixIn3 where
data Inf a b = Nil | a :* b
data Try = C1 Try2
data Try2 = C2 [Int]
data T = MkT [a]
f :: (Inf [Int] (Either Int Int)) -> [Int]
f Nil = []
f ((a :* b@(Left b_1))) = a
f ((a :* b@(Right b_1))) = a
f ((a :* b)) = a
h :: (Inf [Int] (Either Int Int)) -> [Int]
h Nil = []
h ((a@[] :* b)) = a
h ((a@((x : xs)) :* b)) = a
j :: Int -> Try -> [Int]
j v x@(C1 b_1@(C2 b_2)) = []
j v x@(C1 b_1) = []
j v x = []
p :: [a] -> a
p ((x : xs)) = x
| |
87cde71c0511c83173521961f4b662b36cbc25eca99fdcfab44b2296fbeb941e | lambdaisland/kaocha | spec_test_check_test.clj | (ns kaocha.plugin.alpha.spec-test-check-test
(:require [clojure.spec.test.alpha]
[clojure.test :refer [deftest testing is]]
[clojure.tools.cli :as cli]
[kaocha.plugin :as plugin]
[matcher-combinators.test]
[kaocha.plugin.alpha.spec-test-check :as spec-test-check]))
(alias 'stc 'clojure.spec.test.check)
(def suite @#'spec-test-check/default-stc-suite)
(defn run-plugin-hook
[hook init & extra-args]
(let [chain (plugin/load-all [:kaocha.plugin.alpha/spec-test-check])]
(apply plugin/run-hook* chain hook init extra-args)))
(deftest cli-options-test
(let [cli-opts (run-plugin-hook :kaocha.hooks/cli-options [])]
(testing "--[no-]stc-instrumentation"
(is (= {:stc-instrumentation true}
(:options (cli/parse-opts ["--stc-instrumentation"] cli-opts))))
(is (= {:stc-instrumentation false}
(:options (cli/parse-opts ["--no-stc-instrumentation"] cli-opts)))))
(testing "--[no-]stc-asserts"
(is (= {:stc-asserts true}
(:options (cli/parse-opts ["--stc-asserts"] cli-opts))))
(is (= {:stc-asserts false}
(:options (cli/parse-opts ["--no-stc-asserts"] cli-opts)))))
(testing "--stc-num-tests"
(is (= {:stc-num-tests 5}
(:options (cli/parse-opts ["--stc-num-tests" "5"]
cli-opts)))))
(testing "--stc-max-size"
(is (= {:stc-max-size 10}
(:options (cli/parse-opts ["--stc-max-size" "10"]
cli-opts)))))))
(deftest config-test
(is (= {:kaocha/tests [suite]}
(run-plugin-hook :kaocha.hooks/config {})))
(testing "::stc/instrument?"
(is (= {:kaocha/tests [(assoc suite ::stc/instrument? true)]
::stc/instrument? true}
(run-plugin-hook :kaocha.hooks/config {::stc/instrument? true})))
(is (= {:kaocha/tests [(assoc suite ::stc/instrument? false)]
::stc/instrument? false}
(run-plugin-hook :kaocha.hooks/config {::stc/instrument? false})))
(is (= {:kaocha/tests [(assoc suite ::stc/instrument? true)]
::stc/instrument? true
:kaocha/cli-options {:stc-instrumentation true}}
(run-plugin-hook :kaocha.hooks/config
{:kaocha/cli-options {:stc-instrumentation true}})))
(is (= {:kaocha/tests [(assoc suite ::stc/instrument? false)]
::stc/instrument? false
:kaocha/cli-options {:stc-instrumentation false}}
(run-plugin-hook
:kaocha.hooks/config
{:kaocha/cli-options {:stc-instrumentation false}}))))
(testing "::stc/check-asserts?"
(is (= {:kaocha/tests [(assoc suite ::stc/check-asserts? true)]
::stc/check-asserts? true}
(run-plugin-hook :kaocha.hooks/config {::stc/check-asserts? true})))
(is (= {:kaocha/tests [(assoc suite ::stc/check-asserts? false)]
::stc/check-asserts? false}
(run-plugin-hook :kaocha.hooks/config {::stc/check-asserts? false})))
(is (= {:kaocha/tests [(assoc suite ::stc/check-asserts? true)]
::stc/check-asserts? true
:kaocha/cli-options {:stc-asserts true}}
(run-plugin-hook :kaocha.hooks/config
{:kaocha/cli-options {:stc-asserts true}})))
(is (= {:kaocha/tests [(assoc suite ::stc/check-asserts? false)]
::stc/check-asserts? false
:kaocha/cli-options {:stc-asserts false}}
(run-plugin-hook :kaocha.hooks/config
{:kaocha/cli-options {:stc-asserts false}}))))
(testing "::stc/opts"
(is (= {:kaocha/tests [(assoc suite ::stc/opts {:num-tests 5})]
::stc/opts {:num-tests 5}
:kaocha/cli-options {:stc-num-tests 5}}
(run-plugin-hook :kaocha.hooks/config
{:kaocha/cli-options {:stc-num-tests 5}})))
(is (= {:kaocha/tests [(assoc suite ::stc/opts {:max-size 5})]
::stc/opts {:max-size 5}
:kaocha/cli-options {:stc-max-size 5}}
(run-plugin-hook :kaocha.hooks/config
{:kaocha/cli-options {:stc-max-size 5}}))))
(testing "with existing test suites"
(is (= {:kaocha/tests [{:kaocha.testable/type :kaocha.type/spec.test.check
:kaocha.testable/id :my-special-fdefs
::stc/instrument? true
::stc/check-asserts? false
::stc/opts {:num-tests 5
:max-size 5}}
{:kaocha.testable/type :kaocha.type/spec.test.check
:kaocha.testable/id :my-ok-fdefs
::stc/instrument? true
::stc/check-asserts? true
::stc/opts {:num-tests 5
:max-size 5}}
{:kaocha.testable/id :unit
:kaocha.testable/type :kaocha.type/clojure.test}]
::stc/instrument? true
::stc/check-asserts? true
::stc/opts {:num-tests 5
:max-size 5}
:kaocha/cli-options {:stc-instrumentation true
:stc-num-tests 5}}
(run-plugin-hook
:kaocha.hooks/config
{:kaocha/tests [{:kaocha.testable/type :kaocha.type/spec.test.check
:kaocha.testable/id :my-special-fdefs
::stc/check-asserts? false
::stc/instrument? true
::stc/opts {:num-tests 1000}}
{:kaocha.testable/type :kaocha.type/spec.test.check
:kaocha.testable/id :my-ok-fdefs}
{:kaocha.testable/id :unit
:kaocha.testable/type :kaocha.type/clojure.test}]
::stc/check-asserts? true
::stc/opts {:num-tests 10
:max-size 5}
:kaocha/cli-options {:stc-instrumentation true
:stc-num-tests 5}})))))
| null | https://raw.githubusercontent.com/lambdaisland/kaocha/8f18babb732b21e7fb2231e44be4d972c7ab22bc/test/unit/kaocha/plugin/alpha/spec_test_check_test.clj | clojure | (ns kaocha.plugin.alpha.spec-test-check-test
(:require [clojure.spec.test.alpha]
[clojure.test :refer [deftest testing is]]
[clojure.tools.cli :as cli]
[kaocha.plugin :as plugin]
[matcher-combinators.test]
[kaocha.plugin.alpha.spec-test-check :as spec-test-check]))
(alias 'stc 'clojure.spec.test.check)
(def suite @#'spec-test-check/default-stc-suite)
(defn run-plugin-hook
[hook init & extra-args]
(let [chain (plugin/load-all [:kaocha.plugin.alpha/spec-test-check])]
(apply plugin/run-hook* chain hook init extra-args)))
(deftest cli-options-test
(let [cli-opts (run-plugin-hook :kaocha.hooks/cli-options [])]
(testing "--[no-]stc-instrumentation"
(is (= {:stc-instrumentation true}
(:options (cli/parse-opts ["--stc-instrumentation"] cli-opts))))
(is (= {:stc-instrumentation false}
(:options (cli/parse-opts ["--no-stc-instrumentation"] cli-opts)))))
(testing "--[no-]stc-asserts"
(is (= {:stc-asserts true}
(:options (cli/parse-opts ["--stc-asserts"] cli-opts))))
(is (= {:stc-asserts false}
(:options (cli/parse-opts ["--no-stc-asserts"] cli-opts)))))
(testing "--stc-num-tests"
(is (= {:stc-num-tests 5}
(:options (cli/parse-opts ["--stc-num-tests" "5"]
cli-opts)))))
(testing "--stc-max-size"
(is (= {:stc-max-size 10}
(:options (cli/parse-opts ["--stc-max-size" "10"]
cli-opts)))))))
(deftest config-test
(is (= {:kaocha/tests [suite]}
(run-plugin-hook :kaocha.hooks/config {})))
(testing "::stc/instrument?"
(is (= {:kaocha/tests [(assoc suite ::stc/instrument? true)]
::stc/instrument? true}
(run-plugin-hook :kaocha.hooks/config {::stc/instrument? true})))
(is (= {:kaocha/tests [(assoc suite ::stc/instrument? false)]
::stc/instrument? false}
(run-plugin-hook :kaocha.hooks/config {::stc/instrument? false})))
(is (= {:kaocha/tests [(assoc suite ::stc/instrument? true)]
::stc/instrument? true
:kaocha/cli-options {:stc-instrumentation true}}
(run-plugin-hook :kaocha.hooks/config
{:kaocha/cli-options {:stc-instrumentation true}})))
(is (= {:kaocha/tests [(assoc suite ::stc/instrument? false)]
::stc/instrument? false
:kaocha/cli-options {:stc-instrumentation false}}
(run-plugin-hook
:kaocha.hooks/config
{:kaocha/cli-options {:stc-instrumentation false}}))))
(testing "::stc/check-asserts?"
(is (= {:kaocha/tests [(assoc suite ::stc/check-asserts? true)]
::stc/check-asserts? true}
(run-plugin-hook :kaocha.hooks/config {::stc/check-asserts? true})))
(is (= {:kaocha/tests [(assoc suite ::stc/check-asserts? false)]
::stc/check-asserts? false}
(run-plugin-hook :kaocha.hooks/config {::stc/check-asserts? false})))
(is (= {:kaocha/tests [(assoc suite ::stc/check-asserts? true)]
::stc/check-asserts? true
:kaocha/cli-options {:stc-asserts true}}
(run-plugin-hook :kaocha.hooks/config
{:kaocha/cli-options {:stc-asserts true}})))
(is (= {:kaocha/tests [(assoc suite ::stc/check-asserts? false)]
::stc/check-asserts? false
:kaocha/cli-options {:stc-asserts false}}
(run-plugin-hook :kaocha.hooks/config
{:kaocha/cli-options {:stc-asserts false}}))))
(testing "::stc/opts"
(is (= {:kaocha/tests [(assoc suite ::stc/opts {:num-tests 5})]
::stc/opts {:num-tests 5}
:kaocha/cli-options {:stc-num-tests 5}}
(run-plugin-hook :kaocha.hooks/config
{:kaocha/cli-options {:stc-num-tests 5}})))
(is (= {:kaocha/tests [(assoc suite ::stc/opts {:max-size 5})]
::stc/opts {:max-size 5}
:kaocha/cli-options {:stc-max-size 5}}
(run-plugin-hook :kaocha.hooks/config
{:kaocha/cli-options {:stc-max-size 5}}))))
(testing "with existing test suites"
(is (= {:kaocha/tests [{:kaocha.testable/type :kaocha.type/spec.test.check
:kaocha.testable/id :my-special-fdefs
::stc/instrument? true
::stc/check-asserts? false
::stc/opts {:num-tests 5
:max-size 5}}
{:kaocha.testable/type :kaocha.type/spec.test.check
:kaocha.testable/id :my-ok-fdefs
::stc/instrument? true
::stc/check-asserts? true
::stc/opts {:num-tests 5
:max-size 5}}
{:kaocha.testable/id :unit
:kaocha.testable/type :kaocha.type/clojure.test}]
::stc/instrument? true
::stc/check-asserts? true
::stc/opts {:num-tests 5
:max-size 5}
:kaocha/cli-options {:stc-instrumentation true
:stc-num-tests 5}}
(run-plugin-hook
:kaocha.hooks/config
{:kaocha/tests [{:kaocha.testable/type :kaocha.type/spec.test.check
:kaocha.testable/id :my-special-fdefs
::stc/check-asserts? false
::stc/instrument? true
::stc/opts {:num-tests 1000}}
{:kaocha.testable/type :kaocha.type/spec.test.check
:kaocha.testable/id :my-ok-fdefs}
{:kaocha.testable/id :unit
:kaocha.testable/type :kaocha.type/clojure.test}]
::stc/check-asserts? true
::stc/opts {:num-tests 10
:max-size 5}
:kaocha/cli-options {:stc-instrumentation true
:stc-num-tests 5}})))))
| |
ebb33a7b4f9518e7f902b6cd07a6b19d48ae464d181c4d8fa48b71b548a08ad7 | nodfur/os | wisp.lisp | ;; > (defun foo (x) x)
;; '(set-symbol-function foo (lambda (x) x))
(set-symbol-function
(quote defun)
(macro
(name params body)
(cons (quote set-symbol-function)
(cons name
(cons (cons (quote lambda)
(cons params
(cons body nil))) nil)))))
| null | https://raw.githubusercontent.com/nodfur/os/00fd7f3f76fa53938720789969d60217368f7dd7/wisp/wisp.lisp | lisp | > (defun foo (x) x)
'(set-symbol-function foo (lambda (x) x)) |
(set-symbol-function
(quote defun)
(macro
(name params body)
(cons (quote set-symbol-function)
(cons name
(cons (cons (quote lambda)
(cons params
(cons body nil))) nil)))))
|
d3483737601a855f28cb26bef3ec10b4a859460a55debbc106f755f301b47d02 | google-research/dex-lang | AbstractSyntax.hs | Copyright 2022 Google LLC
--
-- Use of this source code is governed by a BSD-style
-- license that can be found in the LICENSE file or at
-- -source/licenses/bsd
The parser is written in two distinct stages :
- concrete syntax parsing using ( in ConcreteSyntax.hs )
-- - conversion of concrete syntax to abstract syntax (this file).
--
We separate these two stages to separate concerns : the concrete
-- syntax deals with grouping (including keywords, primitives, and
-- operator precedence), and the abstract syntax makes sure that the
-- resulting grouping structures are actually valid Dex.
--
-- As an example of the difference, an input like
4 + * 3
-- produces a parse error at the concrete syntax stage: `+` and `*`
-- are both infix operators, so cannot be juxtaposed like that.
-- On the other hand, an input like
def foo ( x + y ) = 4
-- groups just fine, but produces a syntax error at the abstract syntax
-- stage because `(x + y)` is not a valid pattern for a function argument.
--
-- A goal we hope to achieve with this separation is to make the
-- concrete syntax relatively uniform: something like `:`, which
-- denotes different bits of abstract syntax in different contexts,
-- can nonetheless be given a definite operator precedence, and a
reader of should be able to know which substrings of input are
the constitutents of the grammar without having to fully parse
-- it.
--
-- Another goal is more practical: deferring the abstract syntax to a
-- separate traversal means the meaning of a grouping construct like
-- `[]` can depend on what follows after it, without requiring the
parser to have unbounded lookahead . At the
-- character-by-character level, we just parse "group surrounded by
-- square brackets", and then the abstract syntax determines whether
-- to interpret it as a table literal, a table pattern, or a class
-- constraint, depending on where it appears and what follows.
--
-- The separation also turned out to split the code size of the old
parser roughly in half , implying that each of the remaining pieces
-- is less complex on its own. This should make adjusting the syntax,
-- for example to permit grouping parens in more places, that much
-- easier.
module AbstractSyntax (parseExpr, parseDecl, parseBlock, parseTopDeclRepl) where
import Control.Monad (forM, when, liftM2)
import Data.Functor
import Data.Maybe
import Data.Set qualified as S
import Data.String (fromString)
import Data.Text (Text)
import ConcreteSyntax
import Err
import Name
import PPrint ()
import IRVariants
import Types.Primitives
import Types.Source
-- === Converting concrete syntax to abstract syntax ===
parseExpr :: Fallible m => Group -> m (UExpr VoidS)
parseExpr e = liftSyntaxM $ expr e
parseDecl :: Fallible m => CTopDecl -> m (UDecl VoidS VoidS)
parseDecl d = liftSyntaxM $ topDecl d
parseBlock :: Fallible m => CSBlock -> m (UExpr VoidS)
parseBlock b = liftSyntaxM $ block b
liftSyntaxM :: Fallible m => SyntaxM a -> m a
liftSyntaxM cont = liftExcept $ runFallibleM cont
parseTopDeclRepl :: Text -> Maybe SourceBlock
parseTopDeclRepl s = case sbContents b of
UnParseable True _ -> Nothing
_ -> case runFallibleM (checkSourceBlockParses $ sbContents b) of
Success _ -> Just b
Failure _ -> Nothing
where b = mustParseSourceBlock s
# SCC parseTopDeclRepl #
checkSourceBlockParses :: SourceBlock' -> SyntaxM ()
checkSourceBlockParses = \case
TopDecl (WithSrc _ (CSDecl ann (ExprDecl e)))-> do
when (ann /= PlainLet) $ fail "Cannot annotate expressions"
void $ expr e
TopDecl d -> void $ topDecl d
Command _ b -> void $ block b
DeclareForeign _ _ ty -> void $ expr ty
DeclareCustomLinearization _ _ body -> void $ expr body
Misc _ -> return ()
UnParseable _ _ -> return ()
-- === Converting concrete syntax to abstract syntax ===
type SyntaxM = FallibleM
topDecl :: CTopDecl -> SyntaxM (UDecl VoidS VoidS)
topDecl = dropSrc topDecl' where
topDecl' (CSDecl ann d) = decl ann d
topDecl' (CData name args constructors) = do
binders <- toNest . concat <$> mapM dataArg args
constructors' <- mapM dataCon constructors
return $ UDataDefDecl
(UDataDef name binders $
map (\(name', cons) -> (name', UDataDefTrail cons)) constructors')
(fromString name)
(toNest $ map (fromString . fst) constructors')
topDecl' (CStruct name args fields) = do
binders <- toNest . concat <$> mapM dataArg args
fields' <- mapM fieldCon fields
return $ UStructDecl (UStructDef name binders fields') (fromString name)
topDecl' (CInterface supers self methods) = do
supers' <- mapM expr supers
(name, params) <- tyCon self
(methodNames, methodTys) <- unzip <$> forM methods \(nms, ty) -> do
(nm:nms') <- mapM (identifier "interface method name or argument") $ nary Juxtapose nms
ty' <- expr ty
return (fromString nm, UMethodType (Left nms') ty')
let methodNames' = toNest methodNames
return $ UInterface params supers' methodTys
(fromString name) methodNames'
topDecl' (CEffectDecl name methods) = do
let (methodNames, methodPolicies, methodTys) = unzip3 methods
methodTys' <- mapM expr methodTys
return $ UEffectDecl (zipWith UEffectOpType methodPolicies methodTys')
(fromString name) (toNest $ map fromString methodNames)
topDecl' (CHandlerDecl hName effName bodyTyArg args ty methods) = do
let bodyTyArg' = fromString bodyTyArg
args' <- concat <$> (mapM argument $ nary Juxtapose args)
(effs, returnTy) <- optEffects $ effectsToTop ty
methods' <- mapM effectOpDef methods
return $ UHandlerDecl (fromString effName) bodyTyArg' (toNest args')
effs returnTy methods' (fromString hName)
dataArg :: Group -> SyntaxM [(UAnnBinderArrow (AtomNameC CoreIR)) 'VoidS 'VoidS]
dataArg = \case
g@(WithSrc _ (CBracket Square _)) -> map classUAnnBinder <$> multiIfaceBinder g
arg -> do
binder <- optAnnotatedBinder $ (binOptR Colon) arg
return $ [plainUAnnBinder binder]
-- This corresponds to tyConDef in the original parser.
-- tyCon differs from dataCon in how they treat a binding without an
-- annotation. tyCon interprets it as a name that is implicitly of
type TypeKind , and dataCon interprets it as a type that is n't bound
-- to a name.
tyCon :: NameAndArgs -> SyntaxM (UConDef VoidS VoidS)
tyCon = generalCon $ binOptR Colon
-- This corresponds to dataConDef in the original parser.
dataCon :: NameAndArgs -> SyntaxM (UConDef VoidS VoidS)
dataCon = generalCon $ binOptL Colon
fieldCon :: NameAndType -> SyntaxM (SourceName, UType VoidS)
fieldCon (name, ty) = (name,) <$> expr ty
-- generalCon is the common part of tyCon and dataCon.
generalCon :: (Group -> (Maybe Group, Maybe Group))
-> NameAndArgs
-> SyntaxM (UConDef VoidS VoidS)
generalCon binOpt (name, args) = do
args' <- mapM (optAnnotatedBinder . binOpt) args
return $ (name, toNest args')
-- The arguments are the left- and right-hand sides of a binder
-- annotation. Each is, in different contexts, optional. If the
binder is missing , assume UIgnore ; if the anntation is missing ,
assume TypeKind .
optAnnotatedBinder :: (Maybe Group, Maybe Group)
-> SyntaxM (UAnnBinder (AtomNameC CoreIR) VoidS VoidS)
optAnnotatedBinder (lhs, rhs) = do
lhs' <- mapM (identifier "type-annotated binder") lhs
rhs' <- mapM expr rhs
return $ UAnnBinder (maybe UIgnore fromString lhs')
$ fromMaybe tyKind rhs'
where tyKind = ns $ UPrim (UPrimTC TypeKind) []
multiIfaceBinder :: Group -> SyntaxM [UAnnBinder (AtomNameC CoreIR) VoidS VoidS]
multiIfaceBinder = dropSrc \case
(CBracket Square g) -> do tys <- mapM expr $ nary Comma g
return $ map (UAnnBinder UIgnore) tys
g@(CBin (WithSrc _ Juxtapose) _ _) -> concat <$> mapM multiIfaceBinder (nary Juxtapose $ WithSrc Nothing g)
_ -> fail "Invalid class constraint list; expecting one or more bracketed groups"
effectOpDef :: (SourceName, Maybe UResumePolicy, CSBlock) -> SyntaxM (UEffectOpDef VoidS)
effectOpDef (v, Nothing, rhs) =
case v of
"return" -> UReturnOpDef <$> block rhs
_ -> error "impossible"
effectOpDef (v, Just rp, rhs) = UEffectOpDef rp (fromString v) <$> block rhs
decl :: LetAnn -> CSDecl -> SyntaxM (UDecl VoidS VoidS)
decl ann = dropSrc decl' where
decl' (CLet binder body) = ULet ann <$> patOptAnn binder <*> block body
decl' (CBind _ _) = throw SyntaxErr "Arrow binder syntax <- not permitted at the top level, because the binding would have unbounded scope."
decl' (CDef name params maybeTy body) = do
params' <- concat <$> (mapM argument $ nary Juxtapose params)
case maybeTy of
Just ty -> do
(effs, returnTy) <- optEffects $ effectsToTop ty
when (null params' && effs /= UPure) $ throw SyntaxErr "Nullary def can't have effects"
let funTy = buildPiType params' effs returnTy
let lamBinders = params' <&> \(UPatAnnArrow (UPatAnn p _) arr) -> (UPatAnnArrow (UPatAnn p Nothing) arr)
body' <- block body
return $ ULet ann (UPatAnn (fromString name) (Just funTy)) $ buildLam lamBinders body'
Nothing -> do
body' <- block body
return $ ULet ann (UPatAnn (fromString name) Nothing) $ buildLam params' body'
decl' (CInstance header givens methods instName) = do
givens' <- concat <$> (mapM argument $ nary Juxtapose givens)
let msg = "As of October 2022, instance declarations use `given` for the binders and superclasses\n" ++
"For example, `instance Add (a & b) given {a b} [Add a, Add b]`"
clName' <- addContext msg $
identifier "class name in instance declaration" clName
args' <- mapM expr args
methods' <- mapM method methods
let instName' = case instName of
Nothing -> NothingB
(Just n) -> JustB $ fromString n
return $ UInstance (fromString clName') (toNest givens') args' methods' instName'
where
(clName:args) = nary Juxtapose header
decl' (CExpr g) = ULet ann (UPatAnn (nsB UPatIgnore) Nothing) <$> expr g
-- Binder pattern with an optional type annotation
patOptAnn :: Group -> SyntaxM (UPatAnn VoidS VoidS)
patOptAnn (Binary Colon lhs typeAnn) = UPatAnn <$> pat lhs <*> (Just <$> expr typeAnn)
patOptAnn (WithSrc _ (CParens (ExprBlock g))) = patOptAnn g
patOptAnn g = flip UPatAnn Nothing <$> pat g
-- Type annotation with an optional binder pattern
tyOptPat :: Group -> SyntaxM (UPatAnn VoidS VoidS)
tyOptPat = \case
-- Named type
(Binary Colon lhs typeAnn) -> UPatAnn <$> pat lhs <*> (Just <$> expr typeAnn)
-- Pattern in grouping parens.
An anonymous tuple type ( foo & bar ) will group as parens around a
-- Binary Ampersand, which will fall through to the anonymous case
-- as desired.
(WithSrc _ (CParens (ExprBlock g))) -> tyOptPat g
-- Anonymous type
g -> UPatAnn (nsB $ UPatBinder UIgnore) . Just <$> expr g
-- Pattern of a case binder. This treats bare names specially, in
-- that they become (nullary) constructors to match rather than names
-- to bind.
casePat :: Group -> SyntaxM (UPat VoidS VoidS)
casePat = \case
(WithSrc src (CIdentifier name)) -> return $ WithSrcB src $ UPatCon (fromString name) Empty
g -> pat g
pat :: Group -> SyntaxM (UPat VoidS VoidS)
pat = propagateSrcB pat' where
pat' (CBin (WithSrc _ Comma) lhs rhs) = do
lhs' <- pat lhs
rhs' <- pat rhs
return $ UPatPair $ PairB lhs' rhs'
pat' (CBin (WithSrc _ DepComma) lhs rhs) = do
lhs' <- pat lhs
rhs' <- pat rhs
return $ UPatDepPair $ PairB lhs' rhs'
pat' (CBracket Curly g) = case g of
(WithSrc _ CEmpty) -> return $ UPatRecord UEmptyRowPat
_ -> UPatRecord <$> (fieldRowPatList CSEqual $ nary Comma g)
pat' (CBracket Square g) = UPatTable . toNest <$> (mapM pat $ nary Comma g)
-- A single name in parens is also interpreted as a nullary
-- constructor to match
pat' (CParens (ExprBlock g)) = dropSrcB <$> casePat g
pat' CEmpty = return $ UPatUnit UnitB
pat' CHole = return $ UPatBinder UIgnore
pat' (CIdentifier name) = return $ UPatBinder $ fromString name
pat' (CBin (WithSrc _ Juxtapose) lhs rhs) = do
Juxtapose associates to the left , so this is how we get the
first sub - group in the tree .
-- TODO: This makes all juxtaposed patterns mean "constructor name
-- followed by patterns for arguments". This is sensible inside
-- parens, but it's possible for the concrete syntax to produce
-- juxtaposed patterns outside parens as well, for example `def
-- foo (a b:Int)`. Do we want to treat those differently?
let (name:args) = nary Juxtapose $ Binary Juxtapose lhs rhs
name' <- identifier "pattern constructor name" name
args' <- toNest <$> mapM pat args
return $ UPatCon (fromString name') args'
pat' _ = throw SyntaxErr "Illegal pattern"
fieldRowPatList :: Bin' -> [Group] -> SyntaxM (UFieldRowPat VoidS VoidS)
fieldRowPatList bind groups = go groups UEmptyRowPat where
go [] rest = return rest
go (g:gs) rest = case g of
(Binary binder lhs rhs) | binder == bind -> do
header <- case lhs of
(Prefix "@..." field) -> UDynFieldsPat . fromString <$>
identifier "record pattern dynamic remainder name" field
(Prefix "@" field) -> UDynFieldPat . fromString <$>
identifier "record pattern dynamic field name" field
field -> UStaticFieldPat <$> identifier "record pattern field" field
rhs' <- pat rhs
header rhs' <$> go gs rest
(Prefix "..." field) -> case gs of
[] -> case field of
(WithSrc _ CEmpty) -> return $ URemFieldsPat UIgnore
(WithSrc _ CHole) -> return $ URemFieldsPat UIgnore
name -> URemFieldsPat . fromString
<$> identifier "record pattern remainder name" name
_ -> throw SyntaxErr "Ellipsis-pattern must be last"
(WithSrc _ (CParens (ExprBlock g'))) -> go (g':gs) rest
field@(WithSrc src _) -> do
field' <- identifier "record pattern field pun" field
UStaticFieldPat (fromString field') (WithSrcB src $ fromString field') <$> go gs rest
The single argument case supports one annotated binder per set of
-- brackets. The list version supports a list of binders, which are
-- either anonymous, in the case of class constraints (square brackets)
-- or not type annoated, in the other cases.
-- TODO: Why not just allow name / type annotations in the list
-- versions as well?
argument :: Group -> SyntaxM [UPatAnnArrow VoidS VoidS]
argument (Bracketed Curly g) = case g of
(Binary Colon name typ) -> singleArgument ImplicitArrow name typ
_ -> do
pats <- mapM pat $ nary Juxtapose g
return $ map (\x -> UPatAnnArrow (UPatAnn x Nothing) ImplicitArrow) pats
argument (Bracketed Square g) = case g of
(Binary Colon name typ) -> singleArgument ClassArrow name typ
_ -> do
tys <- mapM expr $ nary Comma g
return $ map (\ty -> UPatAnnArrow (UPatAnn (nsB UPatIgnore) (Just ty)) ClassArrow) tys
argument (WithSrc _ (CParens (ExprBlock g))) = explicitArgument g
argument g = explicitArgument g
singleArgument :: Arrow -> Group -> Group -> SyntaxM [UPatAnnArrow VoidS VoidS]
singleArgument arr name typ = do
name' <- pat name
typ' <- expr typ
return $ [UPatAnnArrow (UPatAnn name' (Just typ')) arr]
explicitArgument :: Group -> SyntaxM [UPatAnnArrow VoidS VoidS]
explicitArgument g = case g of
(Binary Colon name typ) -> singleArgument PlainArrow name typ
_ -> do
x <- pat g
return $ [UPatAnnArrow (UPatAnn x Nothing) PlainArrow]
identifier :: String -> Group -> SyntaxM SourceName
identifier ctx = dropSrc identifier' where
identifier' (CIdentifier name) = return name
identifier' _ = throw SyntaxErr $ "Expected " ++ ctx ++ " to be an identifier"
optEffects :: Group -> SyntaxM (UEffectRow VoidS, UExpr VoidS)
optEffects g = case g of
(Binary Juxtapose (Bracketed Curly effs) ty) ->
(,) <$> effects effs <*> expr ty
_ -> (UPure,) <$> expr g
effects :: Group -> SyntaxM (UEffectRow VoidS)
effects g = do
rhs' <- mapM (identifier "effect row remainder variable") rhs
lhs' <- mapM effect $ nary Comma lhs
return $ UEffectRow (S.fromList lhs') $ fmap fromString rhs'
where
(lhs, rhs) = case g of
(Binary Pipe l r) -> (l, Just r)
l -> (l, Nothing)
effect :: Group -> SyntaxM (UEffect VoidS)
effect (WithSrc _ (CParens (ExprBlock g))) = effect g
effect (Binary Juxtapose (Identifier "Read") (Identifier h)) =
return $ URWSEffect Reader $ fromString h
effect (Binary Juxtapose (Identifier "Accum") (Identifier h)) =
return $ URWSEffect Writer $ fromString h
effect (Binary Juxtapose (Identifier "State") (Identifier h)) =
return $ URWSEffect State $ fromString h
effect (Identifier "Except") = return UExceptionEffect
effect (Identifier "IO") = return UIOEffect
effect (Identifier effName) = return $ UUserEffect (fromString effName)
effect _ = throw SyntaxErr "Unexpected effect form; expected one of `Read h`, `Accum h`, `State h`, `Except`, `IO`, or the name of a user-defined effect."
method :: (SourceName, CSBlock) -> SyntaxM (UMethodDef VoidS)
method (name, body) = UMethodDef (fromString name) <$> block body
block :: CSBlock -> SyntaxM (UExpr VoidS)
block (CSBlock []) = throw SyntaxErr "Block must end in expression"
block (CSBlock [ExprDecl g]) = expr g
block (CSBlock ((WithSrc pos (CBind binder rhs)):ds)) = do
binder' <- patOptAnn binder
rhs' <- block rhs
body <- block $ CSBlock ds
return $ WithSrcE pos $ UApp rhs' $ ns $ ULam $ ULamExpr PlainArrow binder' body
block (CSBlock (d@(WithSrc pos _):ds)) = do
d' <- decl PlainLet d
e' <- block $ CSBlock ds
return $ WithSrcE pos $ UDecl $ UDeclExpr d' e'
-- === Concrete to abstract syntax of expressions ===
expr :: Group -> SyntaxM (UExpr VoidS)
expr = propagateSrcE expr' where
expr' CEmpty = return UHole
-- Binders (e.g., in pi types) should not hit this case
expr' (CIdentifier name) = return $ fromString name
expr' (CPrim prim xs) = UPrim prim <$> mapM expr xs
expr' (CNat word) = return $ UNatLit word
expr' (CInt int) = return $ UIntLit int
expr' (CString str) = return $ UApp (fromString "to_list")
$ ns $ UTabCon $ map (ns . charExpr) str
expr' (CChar char) = return $ charExpr char
expr' (CFloat num) = return $ UFloatLit num
expr' CHole = return UHole
expr' (CLabel prefix str) = return $ labelExpr prefix str
expr' (CParens (ExprBlock (WithSrc _ CEmpty))) = return unitExpr
expr' (CParens blk) = dropSrcE <$> block blk
-- Table constructors here. Other uses of square brackets
-- should be detected upstream, before calling expr.
expr' (CBracket Square g) = UTabCon <$> (mapM expr $ nary Comma g)
expr' (CBracket Curly g) = labeledExprs g
expr' (CBin (WithSrc opSrc op) lhs rhs) =
case op of
Juxtapose -> apply mkApp
Dollar -> apply mkApp
IndexingDot -> apply mkTabApp
FieldAccessDot -> do
lhs' <- expr lhs
WithSrc src rhs' <- return rhs
addSrcContext src $ case rhs' of
CIdentifier name -> return $ UFieldAccess lhs' (WithSrc src name)
_ -> throw SyntaxErr "Field must be a name"
DoubleColon -> UTypeAnn <$> (expr lhs) <*> expr rhs
(EvalBinOp s) -> evalOp s
Ampersand -> evalOp "(&)"
DepAmpersand -> do
lhs' <- tyOptPat lhs
UDepPairTy . (UDepPairType lhs') <$> expr rhs
Comma -> evalOp "(,)"
DepComma -> UDepPair <$> (expr lhs) <*> expr rhs
Pipe -> evalOp "(|)"
CSEqual -> throw SyntaxErr "Equal sign must be used as a separator for labels or binders, not a standalone operator"
Question -> throw SyntaxErr "Question mark separates labeled row elements, is not a standalone operator"
Colon -> throw SyntaxErr "Colon separates binders from their type annotations, is not a standalone operator.\nIf you are trying to write a dependent type, use parens: (i:Fin 4) => (..i)"
FatArrow -> do
lhs' <- tyOptPat lhs
UTabPi . (UTabPiExpr lhs') <$> expr rhs
Arrow arr -> do
lhs' <- tyOptPat lhs
(effs, ty) <- optEffects $ effectsToTop rhs
return $ UPi $ UPiExpr arr lhs' effs ty
where
evalOp s = do
app1 <- mkApp (WithSrcE opSrc (fromString s)) <$> expr lhs
UApp app1 <$> expr rhs
apply kind = do
lhs' <- expr lhs
dropSrcE . (kind lhs') <$> expr rhs
expr' (CPrefix name g) =
case name of
".." -> range "RangeTo" <$> expr g
"..<" -> range "RangeToExc" <$> expr g
"+" -> dropSrcE <$> expr g <&> \case
UNatLit i -> UIntLit (fromIntegral i)
UIntLit i -> UIntLit i
UFloatLit i -> UFloatLit i
e -> e
"-" -> dropSrcE <$> expr g <&> \case
UNatLit i -> UIntLit (-(fromIntegral i))
UIntLit i -> UIntLit (-i)
UFloatLit i -> UFloatLit (-i)
TODO propagate source info form ` expr g ` to the nested
-- expression `e`, instead of writing `ns e`.
e -> dropSrcE $ mkApp (ns "neg") $ ns e
_ -> throw SyntaxErr $ "Prefix (" ++ name ++ ") not legal as a bare expression"
where
range :: SourceName -> UExpr VoidS -> UExpr' VoidS
range rangeName lim =
UApp (mkApp (ns $ fromString rangeName) (ns UHole)) lim
expr' (CPostfix name g) =
case name of
".." -> range "RangeFrom" <$> expr g
"<.." -> range "RangeFromExc" <$> expr g
_ -> throw SyntaxErr $ "Postfix (" ++ name ++ ") not legal as a bare expression"
where
range :: SourceName -> UExpr VoidS -> UExpr' VoidS
range rangeName lim =
UApp (mkApp (ns $ fromString rangeName) (ns UHole)) lim
expr' (CLambda args body) =
dropSrcE <$> liftM2 buildLam (concat <$> mapM argument args) (block body)
expr' (CFor kind indices body) = do
let (dir, trailingUnit) = case kind of
KFor -> (Fwd, False)
KFor_ -> (Fwd, True)
KRof -> (Rev, False)
KRof_ -> (Rev, True)
-- TODO: Can we fetch the source position from the error context, to feed into `buildFor`?
e <- buildFor (0, 0) dir <$> mapM patOptAnn indices <*> block body
if trailingUnit
then return $ UDecl $ UDeclExpr (ULet PlainLet (UPatAnn (nsB UPatIgnore) Nothing) e) $ ns $ unitExpr
else return $ dropSrcE e
expr' (CCase scrut alts) = UCase <$> (expr scrut) <*> mapM alternative alts
where alternative (match, body) = UAlt <$> casePat match <*> block body
expr' (CIf p c a) = do
p' <- expr p
c' <- block c
a' <- case a of
Nothing -> return $ ns $ unitExpr
(Just alternative) -> block alternative
return $ UCase p'
[ UAlt (nsB $ UPatCon "True" Empty) c'
, UAlt (nsB $ UPatCon "False" Empty) a']
expr' (CDo blk) = ULam . (ULamExpr PlainArrow (UPatAnn (nsB $ UPatUnit UnitB) Nothing)) <$> block blk
charExpr :: Char -> (UExpr' VoidS)
charExpr c = UPrim (UPrimCon $ Lit $ Word8Lit $ fromIntegral $ fromEnum c) []
unitExpr :: UExpr' VoidS
unitExpr = UPrim (UPrimCon $ ProdCon []) []
labelExpr :: LabelPrefix -> String -> UExpr' VoidS
labelExpr PlainLabel str = ULabel str
labeledExprs :: Group -> SyntaxM (UExpr' VoidS)
-- We treat {} as an empty record, despite its ambiguity.
labeledExprs (WithSrc _ CEmpty) = return $ URecord []
-- Comma, ampersand, question mark, and pipe imply multi-element
-- lists, or a list where an extra separator was used for
-- disambiguation. In any case, within curly braces they are unique:
-- comma means record value, colon means record type, question means
-- labeled row, and pipe means variant type.
labeledExprs g@(Binary Comma _ _) =
URecord <$> (fieldRowList CSEqual $ nary Comma g)
labeledExprs g@(Binary Ampersand _ _) =
URecordTy <$> (fieldRowList Colon $ nary Ampersand g)
labeledExprs g@(Binary Question _ _) =
ULabeledRow <$> (fieldRowList Colon $ nary Question g)
-- If we have a singleton, we can try to disambiguate by the internal
-- separator. Equal always means record.
labeledExprs g@(Binary CSEqual _ _) = URecord . (:[]) <$> oneField CSEqual g
URecordTy , ULabeledRow , and UVariantTy all use colon as the
-- internal separator, so a singleton is ambiguous. Like the previous
-- parser, we disambiguate in favor of records.
labeledExprs g@(Binary Colon _ _) = URecordTy . (:[]) <$> oneField Colon g
-- A bare identifier also parsed in the old parser, as a record value
-- with a single field pun.
labeledExprs (WithSrc src (CIdentifier name)) = return $ URecord $ [fieldPun src name]
labeledExprs _ = throw SyntaxErr "Ambiguous curly-brace expression; needs a , & ? or | to disambiguate"
This is a near - duplicate to fieldRowPatList , but
-- would require (i) a class to pick the constructors to use (e.g.,
-- UDynField vs UDynFieldPat) and (ii) switching between places where
the two structures require subexpressions or subpatterns or
-- identifiers.
fieldRowList :: Bin' -> [Group] -> SyntaxM (UFieldRowElems VoidS)
fieldRowList bind groups = mapM (oneField bind) groups
oneField :: Bin' -> Group -> SyntaxM (UFieldRowElem VoidS)
oneField bind = \case
(Binary binder lhs rhs) | binder == bind -> do
header <- case lhs of
(Prefix "@" field) -> UDynField . fromString
<$> identifier "variable holding dynamic record field" field
field -> UStaticField <$> identifier "record field" field
rhs' <- expr rhs
return $ header rhs'
(Prefix "..." field) -> UDynFields <$> expr field
(WithSrc _ (CParens (ExprBlock g'))) -> oneField bind g'
(WithSrc src (CIdentifier field')) -> return $ fieldPun src field'
(WithSrc src _) -> addSrcContext src $ throw SyntaxErr
$ "Bad field spec. Expected an explicit field `label " ++ pprint bind ++ " expr`, "
++ "a remaining fields expression `... expr`, or a label-field pun `label`."
fieldPun :: SrcPosCtx -> String -> UFieldRowElem VoidS
fieldPun src field = UStaticField (fromString field) (WithSrcE src $ fromString field)
-- === Builders ===
buildPiType :: [UPatAnnArrow VoidS VoidS] -> UEffectRow VoidS -> UType VoidS -> UType VoidS
buildPiType [] UPure ty = ty
buildPiType [] _ _ = error "shouldn't be possible"
buildPiType (UPatAnnArrow p arr : bs) eff resTy = ns case bs of
[] -> UPi $ UPiExpr arr p eff resTy
_ -> UPi $ UPiExpr arr p UPure $ buildPiType bs eff resTy
TODO Does this generalize ? Swap list for Nest ?
buildLam :: [UPatAnnArrow VoidS VoidS] -> UExpr VoidS -> UExpr VoidS
buildLam binders body@(WithSrcE pos _) = case binders of
[] -> body
-- TODO: join with source position of binders too
(UPatAnnArrow b arr):bs -> WithSrcE (joinPos pos' pos) $ ULam lamb
where UPatAnn (WithSrcB pos' _) _ = b
lamb = ULamExpr arr b $ buildLam bs body
TODO Does this generalize ? Swap list for Nest ?
buildFor :: SrcPos -> Direction -> [UPatAnn VoidS VoidS] -> UExpr VoidS -> UExpr VoidS
buildFor pos dir binders body = case binders of
[] -> body
b:bs -> WithSrcE (Just pos) $ UFor dir $ UForExpr b $ buildFor pos dir bs body
-- === Helpers ===
ns :: (a n) -> WithSrcE a n
ns = WithSrcE Nothing
nsB :: (b n l) -> WithSrcB b n l
nsB = WithSrcB Nothing
toNest :: [a VoidS VoidS] -> Nest a VoidS VoidS
toNest = foldr Nest Empty
dropSrc :: (t -> SyntaxM a) -> WithSrc t -> SyntaxM a
dropSrc act (WithSrc src x) = addSrcContext src $ act x
propagateSrcE :: (t -> SyntaxM (e n)) -> WithSrc t -> SyntaxM (WithSrcE e n)
propagateSrcE act (WithSrc src x) = addSrcContext src (WithSrcE src <$> act x)
dropSrcE :: WithSrcE e n -> e n
dropSrcE (WithSrcE _ x) = x
propagateSrcB :: (t -> SyntaxM (binder n l)) -> WithSrc t -> SyntaxM (WithSrcB binder n l)
propagateSrcB act (WithSrc src x) = addSrcContext src (WithSrcB src <$> act x)
dropSrcB :: WithSrcB binder n l -> binder n l
dropSrcB (WithSrcB _ x) = x
joinSrcE :: WithSrcE a1 n1 -> WithSrcE a2 n2 -> a3 n3 -> WithSrcE a3 n3
joinSrcE (WithSrcE p1 _) (WithSrcE p2 _) x = WithSrcE (joinPos p1 p2) x
mkApp :: UExpr (n::S) -> UExpr n -> UExpr n
mkApp f x = joinSrcE f x $ UApp f x
mkTabApp :: UExpr (n::S) -> UExpr n -> UExpr n
mkTabApp f x = joinSrcE f x $ UTabApp f x
If Group is a Binary tree , check the leftmost leaf . If that leaf
is curly braces and its operator is Juxtapose , reassociate the tree
-- to bring it to the top. This re-groups a term like {IO} n=>a as
-- {IO} (n=>a), instead of ({IO} n)=>a, which is how it parses
-- otherwise.
effectsToTop :: Group -> Group
effectsToTop g@(Binary Juxtapose (Bracketed Curly _) _) = g
effectsToTop g@(WithSrc pos (CBin op lhs rhs)) = case effectsToTop lhs of
(WithSrc _ (CBin j@(WithSrc _ Juxtapose) br@(Bracketed Curly _) subRhs)) ->
WithSrc pos (CBin j br (WithSrc (jointPos subRhs rhs) (CBin op subRhs rhs)))
_ -> g
effectsToTop g = g
| null | https://raw.githubusercontent.com/google-research/dex-lang/c5a39c808c1ed19521517efea7e888ac8ad644e7/src/lib/AbstractSyntax.hs | haskell |
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file or at
-source/licenses/bsd
- conversion of concrete syntax to abstract syntax (this file).
syntax deals with grouping (including keywords, primitives, and
operator precedence), and the abstract syntax makes sure that the
resulting grouping structures are actually valid Dex.
As an example of the difference, an input like
produces a parse error at the concrete syntax stage: `+` and `*`
are both infix operators, so cannot be juxtaposed like that.
On the other hand, an input like
groups just fine, but produces a syntax error at the abstract syntax
stage because `(x + y)` is not a valid pattern for a function argument.
A goal we hope to achieve with this separation is to make the
concrete syntax relatively uniform: something like `:`, which
denotes different bits of abstract syntax in different contexts,
can nonetheless be given a definite operator precedence, and a
it.
Another goal is more practical: deferring the abstract syntax to a
separate traversal means the meaning of a grouping construct like
`[]` can depend on what follows after it, without requiring the
character-by-character level, we just parse "group surrounded by
square brackets", and then the abstract syntax determines whether
to interpret it as a table literal, a table pattern, or a class
constraint, depending on where it appears and what follows.
The separation also turned out to split the code size of the old
is less complex on its own. This should make adjusting the syntax,
for example to permit grouping parens in more places, that much
easier.
=== Converting concrete syntax to abstract syntax ===
=== Converting concrete syntax to abstract syntax ===
This corresponds to tyConDef in the original parser.
tyCon differs from dataCon in how they treat a binding without an
annotation. tyCon interprets it as a name that is implicitly of
to a name.
This corresponds to dataConDef in the original parser.
generalCon is the common part of tyCon and dataCon.
The arguments are the left- and right-hand sides of a binder
annotation. Each is, in different contexts, optional. If the
Binder pattern with an optional type annotation
Type annotation with an optional binder pattern
Named type
Pattern in grouping parens.
Binary Ampersand, which will fall through to the anonymous case
as desired.
Anonymous type
Pattern of a case binder. This treats bare names specially, in
that they become (nullary) constructors to match rather than names
to bind.
A single name in parens is also interpreted as a nullary
constructor to match
TODO: This makes all juxtaposed patterns mean "constructor name
followed by patterns for arguments". This is sensible inside
parens, but it's possible for the concrete syntax to produce
juxtaposed patterns outside parens as well, for example `def
foo (a b:Int)`. Do we want to treat those differently?
brackets. The list version supports a list of binders, which are
either anonymous, in the case of class constraints (square brackets)
or not type annoated, in the other cases.
TODO: Why not just allow name / type annotations in the list
versions as well?
=== Concrete to abstract syntax of expressions ===
Binders (e.g., in pi types) should not hit this case
Table constructors here. Other uses of square brackets
should be detected upstream, before calling expr.
expression `e`, instead of writing `ns e`.
TODO: Can we fetch the source position from the error context, to feed into `buildFor`?
We treat {} as an empty record, despite its ambiguity.
Comma, ampersand, question mark, and pipe imply multi-element
lists, or a list where an extra separator was used for
disambiguation. In any case, within curly braces they are unique:
comma means record value, colon means record type, question means
labeled row, and pipe means variant type.
If we have a singleton, we can try to disambiguate by the internal
separator. Equal always means record.
internal separator, so a singleton is ambiguous. Like the previous
parser, we disambiguate in favor of records.
A bare identifier also parsed in the old parser, as a record value
with a single field pun.
would require (i) a class to pick the constructors to use (e.g.,
UDynField vs UDynFieldPat) and (ii) switching between places where
identifiers.
=== Builders ===
TODO: join with source position of binders too
=== Helpers ===
to bring it to the top. This re-groups a term like {IO} n=>a as
{IO} (n=>a), instead of ({IO} n)=>a, which is how it parses
otherwise. | Copyright 2022 Google LLC
The parser is written in two distinct stages :
- concrete syntax parsing using ( in ConcreteSyntax.hs )
We separate these two stages to separate concerns : the concrete
4 + * 3
def foo ( x + y ) = 4
reader of should be able to know which substrings of input are
the constitutents of the grammar without having to fully parse
parser to have unbounded lookahead . At the
parser roughly in half , implying that each of the remaining pieces
module AbstractSyntax (parseExpr, parseDecl, parseBlock, parseTopDeclRepl) where
import Control.Monad (forM, when, liftM2)
import Data.Functor
import Data.Maybe
import Data.Set qualified as S
import Data.String (fromString)
import Data.Text (Text)
import ConcreteSyntax
import Err
import Name
import PPrint ()
import IRVariants
import Types.Primitives
import Types.Source
parseExpr :: Fallible m => Group -> m (UExpr VoidS)
parseExpr e = liftSyntaxM $ expr e
parseDecl :: Fallible m => CTopDecl -> m (UDecl VoidS VoidS)
parseDecl d = liftSyntaxM $ topDecl d
parseBlock :: Fallible m => CSBlock -> m (UExpr VoidS)
parseBlock b = liftSyntaxM $ block b
liftSyntaxM :: Fallible m => SyntaxM a -> m a
liftSyntaxM cont = liftExcept $ runFallibleM cont
parseTopDeclRepl :: Text -> Maybe SourceBlock
parseTopDeclRepl s = case sbContents b of
UnParseable True _ -> Nothing
_ -> case runFallibleM (checkSourceBlockParses $ sbContents b) of
Success _ -> Just b
Failure _ -> Nothing
where b = mustParseSourceBlock s
# SCC parseTopDeclRepl #
checkSourceBlockParses :: SourceBlock' -> SyntaxM ()
checkSourceBlockParses = \case
TopDecl (WithSrc _ (CSDecl ann (ExprDecl e)))-> do
when (ann /= PlainLet) $ fail "Cannot annotate expressions"
void $ expr e
TopDecl d -> void $ topDecl d
Command _ b -> void $ block b
DeclareForeign _ _ ty -> void $ expr ty
DeclareCustomLinearization _ _ body -> void $ expr body
Misc _ -> return ()
UnParseable _ _ -> return ()
type SyntaxM = FallibleM
topDecl :: CTopDecl -> SyntaxM (UDecl VoidS VoidS)
topDecl = dropSrc topDecl' where
topDecl' (CSDecl ann d) = decl ann d
topDecl' (CData name args constructors) = do
binders <- toNest . concat <$> mapM dataArg args
constructors' <- mapM dataCon constructors
return $ UDataDefDecl
(UDataDef name binders $
map (\(name', cons) -> (name', UDataDefTrail cons)) constructors')
(fromString name)
(toNest $ map (fromString . fst) constructors')
topDecl' (CStruct name args fields) = do
binders <- toNest . concat <$> mapM dataArg args
fields' <- mapM fieldCon fields
return $ UStructDecl (UStructDef name binders fields') (fromString name)
topDecl' (CInterface supers self methods) = do
supers' <- mapM expr supers
(name, params) <- tyCon self
(methodNames, methodTys) <- unzip <$> forM methods \(nms, ty) -> do
(nm:nms') <- mapM (identifier "interface method name or argument") $ nary Juxtapose nms
ty' <- expr ty
return (fromString nm, UMethodType (Left nms') ty')
let methodNames' = toNest methodNames
return $ UInterface params supers' methodTys
(fromString name) methodNames'
topDecl' (CEffectDecl name methods) = do
let (methodNames, methodPolicies, methodTys) = unzip3 methods
methodTys' <- mapM expr methodTys
return $ UEffectDecl (zipWith UEffectOpType methodPolicies methodTys')
(fromString name) (toNest $ map fromString methodNames)
topDecl' (CHandlerDecl hName effName bodyTyArg args ty methods) = do
let bodyTyArg' = fromString bodyTyArg
args' <- concat <$> (mapM argument $ nary Juxtapose args)
(effs, returnTy) <- optEffects $ effectsToTop ty
methods' <- mapM effectOpDef methods
return $ UHandlerDecl (fromString effName) bodyTyArg' (toNest args')
effs returnTy methods' (fromString hName)
dataArg :: Group -> SyntaxM [(UAnnBinderArrow (AtomNameC CoreIR)) 'VoidS 'VoidS]
dataArg = \case
g@(WithSrc _ (CBracket Square _)) -> map classUAnnBinder <$> multiIfaceBinder g
arg -> do
binder <- optAnnotatedBinder $ (binOptR Colon) arg
return $ [plainUAnnBinder binder]
type TypeKind , and dataCon interprets it as a type that is n't bound
tyCon :: NameAndArgs -> SyntaxM (UConDef VoidS VoidS)
tyCon = generalCon $ binOptR Colon
dataCon :: NameAndArgs -> SyntaxM (UConDef VoidS VoidS)
dataCon = generalCon $ binOptL Colon
fieldCon :: NameAndType -> SyntaxM (SourceName, UType VoidS)
fieldCon (name, ty) = (name,) <$> expr ty
generalCon :: (Group -> (Maybe Group, Maybe Group))
-> NameAndArgs
-> SyntaxM (UConDef VoidS VoidS)
generalCon binOpt (name, args) = do
args' <- mapM (optAnnotatedBinder . binOpt) args
return $ (name, toNest args')
binder is missing , assume UIgnore ; if the anntation is missing ,
assume TypeKind .
optAnnotatedBinder :: (Maybe Group, Maybe Group)
-> SyntaxM (UAnnBinder (AtomNameC CoreIR) VoidS VoidS)
optAnnotatedBinder (lhs, rhs) = do
lhs' <- mapM (identifier "type-annotated binder") lhs
rhs' <- mapM expr rhs
return $ UAnnBinder (maybe UIgnore fromString lhs')
$ fromMaybe tyKind rhs'
where tyKind = ns $ UPrim (UPrimTC TypeKind) []
multiIfaceBinder :: Group -> SyntaxM [UAnnBinder (AtomNameC CoreIR) VoidS VoidS]
multiIfaceBinder = dropSrc \case
(CBracket Square g) -> do tys <- mapM expr $ nary Comma g
return $ map (UAnnBinder UIgnore) tys
g@(CBin (WithSrc _ Juxtapose) _ _) -> concat <$> mapM multiIfaceBinder (nary Juxtapose $ WithSrc Nothing g)
_ -> fail "Invalid class constraint list; expecting one or more bracketed groups"
effectOpDef :: (SourceName, Maybe UResumePolicy, CSBlock) -> SyntaxM (UEffectOpDef VoidS)
effectOpDef (v, Nothing, rhs) =
case v of
"return" -> UReturnOpDef <$> block rhs
_ -> error "impossible"
effectOpDef (v, Just rp, rhs) = UEffectOpDef rp (fromString v) <$> block rhs
decl :: LetAnn -> CSDecl -> SyntaxM (UDecl VoidS VoidS)
decl ann = dropSrc decl' where
decl' (CLet binder body) = ULet ann <$> patOptAnn binder <*> block body
decl' (CBind _ _) = throw SyntaxErr "Arrow binder syntax <- not permitted at the top level, because the binding would have unbounded scope."
decl' (CDef name params maybeTy body) = do
params' <- concat <$> (mapM argument $ nary Juxtapose params)
case maybeTy of
Just ty -> do
(effs, returnTy) <- optEffects $ effectsToTop ty
when (null params' && effs /= UPure) $ throw SyntaxErr "Nullary def can't have effects"
let funTy = buildPiType params' effs returnTy
let lamBinders = params' <&> \(UPatAnnArrow (UPatAnn p _) arr) -> (UPatAnnArrow (UPatAnn p Nothing) arr)
body' <- block body
return $ ULet ann (UPatAnn (fromString name) (Just funTy)) $ buildLam lamBinders body'
Nothing -> do
body' <- block body
return $ ULet ann (UPatAnn (fromString name) Nothing) $ buildLam params' body'
decl' (CInstance header givens methods instName) = do
givens' <- concat <$> (mapM argument $ nary Juxtapose givens)
let msg = "As of October 2022, instance declarations use `given` for the binders and superclasses\n" ++
"For example, `instance Add (a & b) given {a b} [Add a, Add b]`"
clName' <- addContext msg $
identifier "class name in instance declaration" clName
args' <- mapM expr args
methods' <- mapM method methods
let instName' = case instName of
Nothing -> NothingB
(Just n) -> JustB $ fromString n
return $ UInstance (fromString clName') (toNest givens') args' methods' instName'
where
(clName:args) = nary Juxtapose header
decl' (CExpr g) = ULet ann (UPatAnn (nsB UPatIgnore) Nothing) <$> expr g
patOptAnn :: Group -> SyntaxM (UPatAnn VoidS VoidS)
patOptAnn (Binary Colon lhs typeAnn) = UPatAnn <$> pat lhs <*> (Just <$> expr typeAnn)
patOptAnn (WithSrc _ (CParens (ExprBlock g))) = patOptAnn g
patOptAnn g = flip UPatAnn Nothing <$> pat g
tyOptPat :: Group -> SyntaxM (UPatAnn VoidS VoidS)
tyOptPat = \case
(Binary Colon lhs typeAnn) -> UPatAnn <$> pat lhs <*> (Just <$> expr typeAnn)
An anonymous tuple type ( foo & bar ) will group as parens around a
(WithSrc _ (CParens (ExprBlock g))) -> tyOptPat g
g -> UPatAnn (nsB $ UPatBinder UIgnore) . Just <$> expr g
casePat :: Group -> SyntaxM (UPat VoidS VoidS)
casePat = \case
(WithSrc src (CIdentifier name)) -> return $ WithSrcB src $ UPatCon (fromString name) Empty
g -> pat g
pat :: Group -> SyntaxM (UPat VoidS VoidS)
pat = propagateSrcB pat' where
pat' (CBin (WithSrc _ Comma) lhs rhs) = do
lhs' <- pat lhs
rhs' <- pat rhs
return $ UPatPair $ PairB lhs' rhs'
pat' (CBin (WithSrc _ DepComma) lhs rhs) = do
lhs' <- pat lhs
rhs' <- pat rhs
return $ UPatDepPair $ PairB lhs' rhs'
pat' (CBracket Curly g) = case g of
(WithSrc _ CEmpty) -> return $ UPatRecord UEmptyRowPat
_ -> UPatRecord <$> (fieldRowPatList CSEqual $ nary Comma g)
pat' (CBracket Square g) = UPatTable . toNest <$> (mapM pat $ nary Comma g)
pat' (CParens (ExprBlock g)) = dropSrcB <$> casePat g
pat' CEmpty = return $ UPatUnit UnitB
pat' CHole = return $ UPatBinder UIgnore
pat' (CIdentifier name) = return $ UPatBinder $ fromString name
pat' (CBin (WithSrc _ Juxtapose) lhs rhs) = do
Juxtapose associates to the left , so this is how we get the
first sub - group in the tree .
let (name:args) = nary Juxtapose $ Binary Juxtapose lhs rhs
name' <- identifier "pattern constructor name" name
args' <- toNest <$> mapM pat args
return $ UPatCon (fromString name') args'
pat' _ = throw SyntaxErr "Illegal pattern"
fieldRowPatList :: Bin' -> [Group] -> SyntaxM (UFieldRowPat VoidS VoidS)
fieldRowPatList bind groups = go groups UEmptyRowPat where
go [] rest = return rest
go (g:gs) rest = case g of
(Binary binder lhs rhs) | binder == bind -> do
header <- case lhs of
(Prefix "@..." field) -> UDynFieldsPat . fromString <$>
identifier "record pattern dynamic remainder name" field
(Prefix "@" field) -> UDynFieldPat . fromString <$>
identifier "record pattern dynamic field name" field
field -> UStaticFieldPat <$> identifier "record pattern field" field
rhs' <- pat rhs
header rhs' <$> go gs rest
(Prefix "..." field) -> case gs of
[] -> case field of
(WithSrc _ CEmpty) -> return $ URemFieldsPat UIgnore
(WithSrc _ CHole) -> return $ URemFieldsPat UIgnore
name -> URemFieldsPat . fromString
<$> identifier "record pattern remainder name" name
_ -> throw SyntaxErr "Ellipsis-pattern must be last"
(WithSrc _ (CParens (ExprBlock g'))) -> go (g':gs) rest
field@(WithSrc src _) -> do
field' <- identifier "record pattern field pun" field
UStaticFieldPat (fromString field') (WithSrcB src $ fromString field') <$> go gs rest
The single argument case supports one annotated binder per set of
argument :: Group -> SyntaxM [UPatAnnArrow VoidS VoidS]
argument (Bracketed Curly g) = case g of
(Binary Colon name typ) -> singleArgument ImplicitArrow name typ
_ -> do
pats <- mapM pat $ nary Juxtapose g
return $ map (\x -> UPatAnnArrow (UPatAnn x Nothing) ImplicitArrow) pats
argument (Bracketed Square g) = case g of
(Binary Colon name typ) -> singleArgument ClassArrow name typ
_ -> do
tys <- mapM expr $ nary Comma g
return $ map (\ty -> UPatAnnArrow (UPatAnn (nsB UPatIgnore) (Just ty)) ClassArrow) tys
argument (WithSrc _ (CParens (ExprBlock g))) = explicitArgument g
argument g = explicitArgument g
singleArgument :: Arrow -> Group -> Group -> SyntaxM [UPatAnnArrow VoidS VoidS]
singleArgument arr name typ = do
name' <- pat name
typ' <- expr typ
return $ [UPatAnnArrow (UPatAnn name' (Just typ')) arr]
explicitArgument :: Group -> SyntaxM [UPatAnnArrow VoidS VoidS]
explicitArgument g = case g of
(Binary Colon name typ) -> singleArgument PlainArrow name typ
_ -> do
x <- pat g
return $ [UPatAnnArrow (UPatAnn x Nothing) PlainArrow]
identifier :: String -> Group -> SyntaxM SourceName
identifier ctx = dropSrc identifier' where
identifier' (CIdentifier name) = return name
identifier' _ = throw SyntaxErr $ "Expected " ++ ctx ++ " to be an identifier"
optEffects :: Group -> SyntaxM (UEffectRow VoidS, UExpr VoidS)
optEffects g = case g of
(Binary Juxtapose (Bracketed Curly effs) ty) ->
(,) <$> effects effs <*> expr ty
_ -> (UPure,) <$> expr g
effects :: Group -> SyntaxM (UEffectRow VoidS)
effects g = do
rhs' <- mapM (identifier "effect row remainder variable") rhs
lhs' <- mapM effect $ nary Comma lhs
return $ UEffectRow (S.fromList lhs') $ fmap fromString rhs'
where
(lhs, rhs) = case g of
(Binary Pipe l r) -> (l, Just r)
l -> (l, Nothing)
effect :: Group -> SyntaxM (UEffect VoidS)
effect (WithSrc _ (CParens (ExprBlock g))) = effect g
effect (Binary Juxtapose (Identifier "Read") (Identifier h)) =
return $ URWSEffect Reader $ fromString h
effect (Binary Juxtapose (Identifier "Accum") (Identifier h)) =
return $ URWSEffect Writer $ fromString h
effect (Binary Juxtapose (Identifier "State") (Identifier h)) =
return $ URWSEffect State $ fromString h
effect (Identifier "Except") = return UExceptionEffect
effect (Identifier "IO") = return UIOEffect
effect (Identifier effName) = return $ UUserEffect (fromString effName)
effect _ = throw SyntaxErr "Unexpected effect form; expected one of `Read h`, `Accum h`, `State h`, `Except`, `IO`, or the name of a user-defined effect."
method :: (SourceName, CSBlock) -> SyntaxM (UMethodDef VoidS)
method (name, body) = UMethodDef (fromString name) <$> block body
block :: CSBlock -> SyntaxM (UExpr VoidS)
block (CSBlock []) = throw SyntaxErr "Block must end in expression"
block (CSBlock [ExprDecl g]) = expr g
block (CSBlock ((WithSrc pos (CBind binder rhs)):ds)) = do
binder' <- patOptAnn binder
rhs' <- block rhs
body <- block $ CSBlock ds
return $ WithSrcE pos $ UApp rhs' $ ns $ ULam $ ULamExpr PlainArrow binder' body
block (CSBlock (d@(WithSrc pos _):ds)) = do
d' <- decl PlainLet d
e' <- block $ CSBlock ds
return $ WithSrcE pos $ UDecl $ UDeclExpr d' e'
expr :: Group -> SyntaxM (UExpr VoidS)
expr = propagateSrcE expr' where
expr' CEmpty = return UHole
expr' (CIdentifier name) = return $ fromString name
expr' (CPrim prim xs) = UPrim prim <$> mapM expr xs
expr' (CNat word) = return $ UNatLit word
expr' (CInt int) = return $ UIntLit int
expr' (CString str) = return $ UApp (fromString "to_list")
$ ns $ UTabCon $ map (ns . charExpr) str
expr' (CChar char) = return $ charExpr char
expr' (CFloat num) = return $ UFloatLit num
expr' CHole = return UHole
expr' (CLabel prefix str) = return $ labelExpr prefix str
expr' (CParens (ExprBlock (WithSrc _ CEmpty))) = return unitExpr
expr' (CParens blk) = dropSrcE <$> block blk
expr' (CBracket Square g) = UTabCon <$> (mapM expr $ nary Comma g)
expr' (CBracket Curly g) = labeledExprs g
expr' (CBin (WithSrc opSrc op) lhs rhs) =
case op of
Juxtapose -> apply mkApp
Dollar -> apply mkApp
IndexingDot -> apply mkTabApp
FieldAccessDot -> do
lhs' <- expr lhs
WithSrc src rhs' <- return rhs
addSrcContext src $ case rhs' of
CIdentifier name -> return $ UFieldAccess lhs' (WithSrc src name)
_ -> throw SyntaxErr "Field must be a name"
DoubleColon -> UTypeAnn <$> (expr lhs) <*> expr rhs
(EvalBinOp s) -> evalOp s
Ampersand -> evalOp "(&)"
DepAmpersand -> do
lhs' <- tyOptPat lhs
UDepPairTy . (UDepPairType lhs') <$> expr rhs
Comma -> evalOp "(,)"
DepComma -> UDepPair <$> (expr lhs) <*> expr rhs
Pipe -> evalOp "(|)"
CSEqual -> throw SyntaxErr "Equal sign must be used as a separator for labels or binders, not a standalone operator"
Question -> throw SyntaxErr "Question mark separates labeled row elements, is not a standalone operator"
Colon -> throw SyntaxErr "Colon separates binders from their type annotations, is not a standalone operator.\nIf you are trying to write a dependent type, use parens: (i:Fin 4) => (..i)"
FatArrow -> do
lhs' <- tyOptPat lhs
UTabPi . (UTabPiExpr lhs') <$> expr rhs
Arrow arr -> do
lhs' <- tyOptPat lhs
(effs, ty) <- optEffects $ effectsToTop rhs
return $ UPi $ UPiExpr arr lhs' effs ty
where
evalOp s = do
app1 <- mkApp (WithSrcE opSrc (fromString s)) <$> expr lhs
UApp app1 <$> expr rhs
apply kind = do
lhs' <- expr lhs
dropSrcE . (kind lhs') <$> expr rhs
expr' (CPrefix name g) =
case name of
".." -> range "RangeTo" <$> expr g
"..<" -> range "RangeToExc" <$> expr g
"+" -> dropSrcE <$> expr g <&> \case
UNatLit i -> UIntLit (fromIntegral i)
UIntLit i -> UIntLit i
UFloatLit i -> UFloatLit i
e -> e
"-" -> dropSrcE <$> expr g <&> \case
UNatLit i -> UIntLit (-(fromIntegral i))
UIntLit i -> UIntLit (-i)
UFloatLit i -> UFloatLit (-i)
TODO propagate source info form ` expr g ` to the nested
e -> dropSrcE $ mkApp (ns "neg") $ ns e
_ -> throw SyntaxErr $ "Prefix (" ++ name ++ ") not legal as a bare expression"
where
range :: SourceName -> UExpr VoidS -> UExpr' VoidS
range rangeName lim =
UApp (mkApp (ns $ fromString rangeName) (ns UHole)) lim
expr' (CPostfix name g) =
case name of
".." -> range "RangeFrom" <$> expr g
"<.." -> range "RangeFromExc" <$> expr g
_ -> throw SyntaxErr $ "Postfix (" ++ name ++ ") not legal as a bare expression"
where
range :: SourceName -> UExpr VoidS -> UExpr' VoidS
range rangeName lim =
UApp (mkApp (ns $ fromString rangeName) (ns UHole)) lim
expr' (CLambda args body) =
dropSrcE <$> liftM2 buildLam (concat <$> mapM argument args) (block body)
expr' (CFor kind indices body) = do
let (dir, trailingUnit) = case kind of
KFor -> (Fwd, False)
KFor_ -> (Fwd, True)
KRof -> (Rev, False)
KRof_ -> (Rev, True)
e <- buildFor (0, 0) dir <$> mapM patOptAnn indices <*> block body
if trailingUnit
then return $ UDecl $ UDeclExpr (ULet PlainLet (UPatAnn (nsB UPatIgnore) Nothing) e) $ ns $ unitExpr
else return $ dropSrcE e
expr' (CCase scrut alts) = UCase <$> (expr scrut) <*> mapM alternative alts
where alternative (match, body) = UAlt <$> casePat match <*> block body
expr' (CIf p c a) = do
p' <- expr p
c' <- block c
a' <- case a of
Nothing -> return $ ns $ unitExpr
(Just alternative) -> block alternative
return $ UCase p'
[ UAlt (nsB $ UPatCon "True" Empty) c'
, UAlt (nsB $ UPatCon "False" Empty) a']
expr' (CDo blk) = ULam . (ULamExpr PlainArrow (UPatAnn (nsB $ UPatUnit UnitB) Nothing)) <$> block blk
charExpr :: Char -> (UExpr' VoidS)
charExpr c = UPrim (UPrimCon $ Lit $ Word8Lit $ fromIntegral $ fromEnum c) []
unitExpr :: UExpr' VoidS
unitExpr = UPrim (UPrimCon $ ProdCon []) []
labelExpr :: LabelPrefix -> String -> UExpr' VoidS
labelExpr PlainLabel str = ULabel str
labeledExprs :: Group -> SyntaxM (UExpr' VoidS)
labeledExprs (WithSrc _ CEmpty) = return $ URecord []
labeledExprs g@(Binary Comma _ _) =
URecord <$> (fieldRowList CSEqual $ nary Comma g)
labeledExprs g@(Binary Ampersand _ _) =
URecordTy <$> (fieldRowList Colon $ nary Ampersand g)
labeledExprs g@(Binary Question _ _) =
ULabeledRow <$> (fieldRowList Colon $ nary Question g)
labeledExprs g@(Binary CSEqual _ _) = URecord . (:[]) <$> oneField CSEqual g
URecordTy , ULabeledRow , and UVariantTy all use colon as the
labeledExprs g@(Binary Colon _ _) = URecordTy . (:[]) <$> oneField Colon g
labeledExprs (WithSrc src (CIdentifier name)) = return $ URecord $ [fieldPun src name]
labeledExprs _ = throw SyntaxErr "Ambiguous curly-brace expression; needs a , & ? or | to disambiguate"
This is a near - duplicate to fieldRowPatList , but
the two structures require subexpressions or subpatterns or
fieldRowList :: Bin' -> [Group] -> SyntaxM (UFieldRowElems VoidS)
fieldRowList bind groups = mapM (oneField bind) groups
oneField :: Bin' -> Group -> SyntaxM (UFieldRowElem VoidS)
oneField bind = \case
(Binary binder lhs rhs) | binder == bind -> do
header <- case lhs of
(Prefix "@" field) -> UDynField . fromString
<$> identifier "variable holding dynamic record field" field
field -> UStaticField <$> identifier "record field" field
rhs' <- expr rhs
return $ header rhs'
(Prefix "..." field) -> UDynFields <$> expr field
(WithSrc _ (CParens (ExprBlock g'))) -> oneField bind g'
(WithSrc src (CIdentifier field')) -> return $ fieldPun src field'
(WithSrc src _) -> addSrcContext src $ throw SyntaxErr
$ "Bad field spec. Expected an explicit field `label " ++ pprint bind ++ " expr`, "
++ "a remaining fields expression `... expr`, or a label-field pun `label`."
fieldPun :: SrcPosCtx -> String -> UFieldRowElem VoidS
fieldPun src field = UStaticField (fromString field) (WithSrcE src $ fromString field)
buildPiType :: [UPatAnnArrow VoidS VoidS] -> UEffectRow VoidS -> UType VoidS -> UType VoidS
buildPiType [] UPure ty = ty
buildPiType [] _ _ = error "shouldn't be possible"
buildPiType (UPatAnnArrow p arr : bs) eff resTy = ns case bs of
[] -> UPi $ UPiExpr arr p eff resTy
_ -> UPi $ UPiExpr arr p UPure $ buildPiType bs eff resTy
TODO Does this generalize ? Swap list for Nest ?
buildLam :: [UPatAnnArrow VoidS VoidS] -> UExpr VoidS -> UExpr VoidS
buildLam binders body@(WithSrcE pos _) = case binders of
[] -> body
(UPatAnnArrow b arr):bs -> WithSrcE (joinPos pos' pos) $ ULam lamb
where UPatAnn (WithSrcB pos' _) _ = b
lamb = ULamExpr arr b $ buildLam bs body
TODO Does this generalize ? Swap list for Nest ?
buildFor :: SrcPos -> Direction -> [UPatAnn VoidS VoidS] -> UExpr VoidS -> UExpr VoidS
buildFor pos dir binders body = case binders of
[] -> body
b:bs -> WithSrcE (Just pos) $ UFor dir $ UForExpr b $ buildFor pos dir bs body
ns :: (a n) -> WithSrcE a n
ns = WithSrcE Nothing
nsB :: (b n l) -> WithSrcB b n l
nsB = WithSrcB Nothing
toNest :: [a VoidS VoidS] -> Nest a VoidS VoidS
toNest = foldr Nest Empty
dropSrc :: (t -> SyntaxM a) -> WithSrc t -> SyntaxM a
dropSrc act (WithSrc src x) = addSrcContext src $ act x
propagateSrcE :: (t -> SyntaxM (e n)) -> WithSrc t -> SyntaxM (WithSrcE e n)
propagateSrcE act (WithSrc src x) = addSrcContext src (WithSrcE src <$> act x)
dropSrcE :: WithSrcE e n -> e n
dropSrcE (WithSrcE _ x) = x
propagateSrcB :: (t -> SyntaxM (binder n l)) -> WithSrc t -> SyntaxM (WithSrcB binder n l)
propagateSrcB act (WithSrc src x) = addSrcContext src (WithSrcB src <$> act x)
dropSrcB :: WithSrcB binder n l -> binder n l
dropSrcB (WithSrcB _ x) = x
joinSrcE :: WithSrcE a1 n1 -> WithSrcE a2 n2 -> a3 n3 -> WithSrcE a3 n3
joinSrcE (WithSrcE p1 _) (WithSrcE p2 _) x = WithSrcE (joinPos p1 p2) x
mkApp :: UExpr (n::S) -> UExpr n -> UExpr n
mkApp f x = joinSrcE f x $ UApp f x
mkTabApp :: UExpr (n::S) -> UExpr n -> UExpr n
mkTabApp f x = joinSrcE f x $ UTabApp f x
If Group is a Binary tree , check the leftmost leaf . If that leaf
is curly braces and its operator is Juxtapose , reassociate the tree
effectsToTop :: Group -> Group
effectsToTop g@(Binary Juxtapose (Bracketed Curly _) _) = g
effectsToTop g@(WithSrc pos (CBin op lhs rhs)) = case effectsToTop lhs of
(WithSrc _ (CBin j@(WithSrc _ Juxtapose) br@(Bracketed Curly _) subRhs)) ->
WithSrc pos (CBin j br (WithSrc (jointPos subRhs rhs) (CBin op subRhs rhs)))
_ -> g
effectsToTop g = g
|
2c06e201f38ab6a41253baffac1ac5ec40b8729c55f5b5c71c566f44e93c5faa | lspitzner/brittany | Test495.hs | -- brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft }
func =
let
foo = True
b = False
in return ()
| null | https://raw.githubusercontent.com/lspitzner/brittany/a15eed5f3608bf1fa7084fcf008c6ecb79542562/data/Test495.hs | haskell | brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft } | func =
let
foo = True
b = False
in return ()
|
b5035ff6bd2b07cac25b67b44e3c1b1603261e537a70050865a17b331883eb32 | evilbinary/scheme-lib | bytenumb.scm | " bytenumb.scm " Byte integer and IEEE floating - point conversions .
Copyright ( C ) 2003
;
;Permission to copy this software, to modify it, to redistribute it,
;to distribute modified versions, and to use it for any purpose is
;granted, subject to the following restrictions and understandings.
;
1 . Any copy made of this software must include this copyright notice
;in full.
;
2 . I have made no warranty or representation that the operation of
;this software will be error-free, and I am under no obligation to
;provide any services, by way of maintenance, update, or otherwise.
;
3 . In conjunction with products arising from the use of this
;material, there shall be no use of my name in any advertising,
;promotional, or sales literature without prior written consent in
;each case.
(require 'byte)
(require 'logical)
;;@code{(require 'byte-number)}
;;@ftindex byte-number
;;@noindent
;;The multi-byte sequences produced and used by numeric conversion
;;routines are always big-endian. Endianness can be changed during
reading and writing bytes using } and
;;@code{write-bytes} @xref{Byte, read-bytes}.
;;
;;@noindent
;;The sign of the length argument to bytes/integer conversion
;;procedures determines the signedness of the number.
;;@body
Converts the first @code{(abs @var{n } ) } bytes of big - endian @1 array
to an integer . If @2 is negative then the integer coded by the
;;bytes are treated as two's-complement (can be negative).
;;
;;@example
( bytes->integer ( bytes 0 0 0 15 ) -4 ) @result { } 15
( bytes->integer ( bytes 0 0 0 15 ) 4 ) @result { } 15
( bytes->integer ( bytes 255 255 255 255 ) -4 ) @result { } -1
( bytes->integer ( bytes 255 255 255 255 ) 4 ) @result { } 4294967295
( bytes->integer ( bytes 128 0 0 0 ) -4 ) @result { } -2147483648
( bytes->integer ( bytes 128 0 0 0 ) 4 ) @result { } 2147483648
;;@end example
(define (bytes->integer bytes n)
(define cnt (abs n))
(cond ((zero? n) 0)
((and (negative? n) (> (byte-ref bytes 0) 127))
(do ((lng (- 255 (byte-ref bytes 0))
(+ (- 255 (byte-ref bytes idx)) (* 256 lng)))
(idx 1 (+ 1 idx)))
((>= idx cnt) (- -1 lng))))
(else
(do ((lng (byte-ref bytes 0)
(+ (byte-ref bytes idx) (* 256 lng)))
(idx 1 (+ 1 idx)))
((>= idx cnt) lng)))))
;;@body
;;Converts the integer @1 to a byte-array of @code{(abs @var{n})}
bytes . If @1 and @2 are both negative , then the bytes in the
;;returned array are coded two's-complement.
;;
;;@example
( bytes->list ( integer->bytes 15 -4 ) ) @result { } ( 0 0 0 15 )
( bytes->list ( integer->bytes 15 4 ) ) @result { } ( 0 0 0 15 )
( bytes->list ( integer->bytes -1 -4 ) ) @result { } ( 255 255 255 255 )
( bytes->list ( integer->bytes 4294967295 4 ) ) @result { } ( 255 255 255 255 )
( bytes->list ( integer->bytes -2147483648 -4 ) ) @result { } ( 128 0 0 0 )
( bytes->list ( integer->bytes 2147483648 4 ) ) @result { } ( 128 0 0 0 )
;;@end example
(define (integer->bytes n len)
(define bytes (make-bytes (abs len)))
(cond ((and (negative? n) (negative? len))
(do ((idx (+ -1 (abs len)) (+ -1 idx))
(res (- -1 n) (quotient res 256)))
((negative? idx) bytes)
(byte-set! bytes idx (- 255 (modulo res 256)))))
(else
(do ((idx (+ -1 (abs len)) (+ -1 idx))
(res n (quotient res 256)))
((negative? idx) bytes)
(byte-set! bytes idx (modulo res 256))))))
;;@body
@1 must be a 4 - element byte - array . @0 calculates and returns the
value of @1 interpreted as a big - endian IEEE 4 - byte ( 32 - bit ) number .
(define (bytes->ieee-float bytes)
(define zero (or (string->number "0.0") 0))
(define one (or (string->number "1.0") 1))
(define len (bytes-length bytes))
(define S (logbit? 7 (byte-ref bytes 0)))
(define E (+ (ash (logand #x7F (byte-ref bytes 0)) 1)
(ash (logand #x80 (byte-ref bytes 1)) -7)))
(if (not (eqv? 4 len))
(slib:error 'bytes->ieee-float 'wrong 'length len))
(do ((F (byte-ref bytes (+ -1 len))
(+ (byte-ref bytes idx) (/ F 256)))
(idx (+ -2 len) (+ -1 idx)))
((<= idx 1)
(set! F (/ (+ (logand #x7F (byte-ref bytes 1)) (/ F 256)) 128))
(cond ((< 0 E 255) (* (if S (- one) one) (expt 2 (- E 127)) (+ 1 F)))
((zero? E)
(if (zero? F)
(if S (- zero) zero)
(* (if S (- one) one) (expt 2 -126) F)))
E must be 255
((not (zero? F)) (/ zero zero))
(else (/ (if S (- one) one) zero))))))
;; S EEEEEEE E FFFFFFF FFFFFFFF FFFFFFFF
;; ========= ========= ======== ========
;; 0 1 8 9 31
;;@example
( - float ( bytes 0 0 0 0 ) ) @result { } 0.0
( - float ( bytes # x80 0 0 0 ) ) @result { } -0.0
( - float ( bytes # x40 0 0 0 ) ) @result { } 2.0
( - float ( bytes # x40 # xd0 0 0 ) ) @result { } 6.5
( - float ( bytes # xc0 # xd0 0 0 ) ) @result { } -6.5
;;
( - float ( bytes 0 # x80 0 0 ) ) @result { } 11.754943508222875e-39
( - float ( bytes 0 # x40 0 0 ) ) @result { } 5.877471754111437e-39
( - float ( bytes 0 0 0 1 ) ) @result { } 1.401298464324817e-45
;;
( - float ( bytes # xff # x80 0 0 ) ) @result { } -inf.0
( - float ( bytes # x7f # x80 0 0 ) ) @result { } + inf.0
( - float ( bytes # x7f # x80 0 1 ) ) @result { } 0/0
( - float ( bytes # x7f # xc0 0 0 ) ) @result { } 0/0
;;@end example
;;@body
@1 must be a 8 - element byte - array . @0 calculates and returns the
value of @1 interpreted as a big - endian IEEE 8 - byte ( 64 - bit ) number .
(define (bytes->ieee-double bytes)
(define zero (or (string->number "0.0") 0))
(define one (or (string->number "1.0") 1))
(define len (bytes-length bytes))
(define S (logbit? 7 (byte-ref bytes 0)))
(define E (+ (ash (logand #x7F (byte-ref bytes 0)) 4)
(ash (logand #xF0 (byte-ref bytes 1)) -4)))
(if (not (eqv? 8 len))
(slib:error 'bytes->ieee-double 'wrong 'length len))
(do ((F (byte-ref bytes (+ -1 len))
(+ (byte-ref bytes idx) (/ F 256)))
(idx (+ -2 len) (+ -1 idx)))
((<= idx 1)
(set! F (/ (+ (logand #x0F (byte-ref bytes 1)) (/ F 256)) 16))
(cond ((< 0 E 2047) (* (if S (- one) one) (expt 2 (- E 1023)) (+ 1 F)))
((zero? E)
(if (zero? F)
(if S (- zero) zero)
(* (if S (- one) one) (expt 2 -1022) F)))
E must be 2047
((not (zero? F)) (/ zero zero))
(else (/ (if S (- one) one) zero))))))
;; S EEEEEEE EEEE FFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF
;; ========= ========= ======== ======== ======== ======== ======== ========
0 1 11 12 63
;;@example
( - double ( bytes 0 0 0 0 0 0 0 0 ) ) @result { } 0.0
( - double ( bytes # x80 0 0 0 0 0 0 0 ) ) @result { } -0.0
( - double ( bytes # x40 0 0 0 0 0 0 0 ) ) @result { } 2.0
( - double ( bytes # x40 # x1A 0 0 0 0 0 0 ) ) @result { } 6.5
( - double ( bytes # xC0 # x1A 0 0 0 0 0 0 ) ) @result { } -6.5
;;
( - double ( bytes 0 8 0 0 0 0 0 0 ) ) @result { } 11.125369292536006e-309
( - double ( bytes 0 4 0 0 0 0 0 0 ) ) @result { } 5.562684646268003e-309
( - double ( bytes 0 0 0 0 0 0 0 1 ) ) @result { } 4.0e-324
;;
( - double ( list->bytes ' ( 127 239 255 255 255 255 255 255 ) ) ) 179.76931348623157e306
( - double ( bytes # xFF # xF0 0 0 0 0 0 0 ) ) @result { } -inf.0
( - double ( bytes # x7F # xF0 0 0 0 0 0 0 ) ) @result { } + inf.0
( - double ( bytes # x7F # xF8 0 0 0 0 0 0 ) ) @result { } 0/0
;;@end example
@args x
Returns a 4 - element byte - array encoding the IEEE single - precision
;;floating-point of @1.
(define ieee-float->bytes
(let ((exactify (if (provided? 'inexact) inexact->exact identity)))
(lambda (flt)
(define byts (make-bytes 4 0))
(define S (and (real? flt) (negative? (if (zero? flt) (/ flt) flt))))
(define (scale flt scl)
(cond ((zero? scl) (out (/ flt 2) scl))
((>= flt 16)
(let ((flt/16 (/ flt 16)))
(cond ((= flt/16 flt)
(byte-set! byts 0 (if S #xFF #x7F))
(byte-set! byts 1 #x80)
byts)
(else (scale flt/16 (+ scl 4))))))
((>= flt 2) (scale (/ flt 2) (+ scl 1)))
((and (>= scl 4)
(< (* 16 flt) 1)) (scale (* flt 16) (+ scl -4)))
((< flt 1) (scale (* flt 2) (+ scl -1)))
(else (out (+ -1 flt) scl))))
(define (out flt scl)
(do ((flt (* 128 flt) (* 256 (- flt val)))
(val (exactify (floor (* 128 flt)))
(exactify (floor (* 256 (- flt val)))))
(idx 1 (+ 1 idx)))
((> idx 3)
(byte-set! byts 1 (bitwise-if #x80 (ash scl 7) (byte-ref byts 1)))
(byte-set! byts 0 (+ (if S 128 0) (ash scl -1)))
byts)
(byte-set! byts idx val)))
(set! flt (magnitude flt))
(cond ((zero? flt) (if S (byte-set! byts 0 #x80)) byts)
((or (not (real? flt))
(not (= flt flt)))
(byte-set! byts 0 (if S #xFF #x7F))
(byte-set! byts 1 #xC0)
byts)
(else (scale flt 127))))))
;;@example
( bytes->list ( - float->bytes 0.0 ) ) @result { } ( 0 0 0 0 )
( bytes->list ( ) ) @result { } ( 128 0 0 0 )
( bytes->list ( - float->bytes 2.0 ) ) @result { } ( 64 0 0 0 )
( bytes->list ( ieee - float->bytes 6.5 ) ) @result { } ( 64 208 0 0 )
( bytes->list ( -6.5 ) ) @result { } ( 192 208 0 0 )
;;
( bytes->list ( - float->bytes 11.754943508222875e-39 ) ) @result { } ( 0 128 0 0 )
( bytes->list ( - float->bytes 5.877471754111438e-39 ) ) @result { } ( 0 64 0 0 )
( bytes->list ( - float->bytes 1.401298464324817e-45 ) ) @result { } ( 0 0 0 1 )
;;
( bytes->list ( ieee - float->bytes -inf.0 ) ) @result { } ( 255 128 0 0 )
( bytes->list ( + inf.0 ) ) @result { } ( 127 128 0 0 )
( bytes->list ( ieee - float->bytes 0/0 ) ) @result { } ( 127 192 0 0 )
;;@end example
@args x
Returns a 8 - element byte - array encoding the IEEE double - precision
;;floating-point of @1.
(define ieee-double->bytes
(let ((exactify (if (provided? 'inexact) inexact->exact identity)))
(lambda (flt)
(define byts (make-bytes 8 0))
(define S (and (real? flt) (negative? (if (zero? flt) (/ flt) flt))))
(define (scale flt scl)
(cond ((zero? scl) (out (/ flt 2) scl))
((>= flt 16)
(let ((flt/16 (/ flt 16)))
(cond ((= flt/16 flt)
(byte-set! byts 0 (if S #xFF #x7F))
(byte-set! byts 1 #xF0)
byts)
(else (scale flt/16 (+ scl 4))))))
((>= flt 2) (scale (/ flt 2) (+ scl 1)))
((and (>= scl 4)
(< (* 16 flt) 1)) (scale (* flt 16) (+ scl -4)))
((< flt 1) (scale (* flt 2) (+ scl -1)))
(else (out (+ -1 flt) scl))))
(define (out flt scl)
(do ((flt (* 16 flt) (* 256 (- flt val)))
(val (exactify (floor (* 16 flt)))
(exactify (floor (* 256 (- flt val)))))
(idx 1 (+ 1 idx)))
((> idx 7)
(byte-set! byts 1 (bitwise-if #xF0 (ash scl 4) (byte-ref byts 1)))
(byte-set! byts 0 (+ (if S 128 0) (ash scl -4)))
byts)
(byte-set! byts idx val)))
(set! flt (magnitude flt))
(cond ((zero? flt) (if S (byte-set! byts 0 #x80)) byts)
((or (not (real? flt))
(not (= flt flt)))
(byte-set! byts 0 #x7F)
(byte-set! byts 1 #xF8)
byts)
(else (scale flt 1023))))))
;;@example
( bytes->list ( ieee - double->bytes 0.0 ) ) @result { } ( 0 0 0 0 0 0 0 0 )
( bytes->list ( ieee - double->bytes -0.0 ) ) @result { } ( 128 0 0 0 0 0 0 0 )
( bytes->list ( - double->bytes 2.0 ) ) @result { } ( 64 0 0 0 0 0 0 0 )
( bytes->list ( ieee - double->bytes 6.5 ) ) @result { } ( 64 26 0 0 0 0 0 0 )
( bytes->list ( - double->bytes -6.5 ) ) @result { } ( 192 26 0 0 0 0 0 0 )
;;
( bytes->list ( - double->bytes 11.125369292536006e-309 ) )
@result { } ( 0 8 0 0 0 0 0 0 )
( bytes->list ( - double->bytes 5.562684646268003e-309 ) )
@result { } ( 0 4 0 0 0 0 0 0 )
( bytes->list ( ieee - double->bytes 4.0e-324 ) )
;; @result{} ( 0 0 0 0 0 0 0 1)
;;
( bytes->list ( ieee - double->bytes -inf.0 ) ) @result { } ( 255 240 0 0 0 0 0 0 )
( bytes->list ( - double->bytes + inf.0 ) ) @result { } ( 127 240 0 0 0 0 0 0 )
( bytes->list ( - double->bytes 0/0 ) ) @result { } ( 127 248 0 0 0 0 0 0 )
;;@end example
Collation Order
;;
;;@noindent
The < ? } ordering of big - endian byte - array
representations of fixed and IEEE floating - point numbers agrees with
;;the numerical ordering only when those numbers are non-negative.
;;
;;@noindent
;;Straighforward modification of these formats can extend the
;;byte-collating order to work for their entire ranges. This
;;agreement enables the full range of numbers as keys in
- sequential - access - method } databases .
;;@body
Modifies sign bit of @1 so that < ? } ordering of
two's - complement byte - vectors matches numerical order . @0 returns
;;@1 and is its own functional inverse.
(define (integer-byte-collate! byte-vector)
(byte-set! byte-vector 0 (logxor #x80 (byte-ref byte-vector 0)))
byte-vector)
;;@body
Returns copy of @1 with sign bit modified so that < ? }
;;ordering of two's-complement byte-vectors matches numerical order.
@0 is its own functional inverse .
(define (integer-byte-collate byte-vector)
(integer-byte-collate! (bytes-copy byte-vector)))
;;@body
Modifies @1 so that < ? } ordering of IEEE floating - point
byte - vectors matches numerical order . @0 returns @1 .
(define (ieee-byte-collate! byte-vector)
(cond ((logtest #x80 (byte-ref byte-vector 0))
(do ((idx (+ -1 (bytes-length byte-vector)) (+ -1 idx)))
((negative? idx))
(byte-set! byte-vector idx
(logxor #xFF (byte-ref byte-vector idx)))))
(else
(byte-set! byte-vector 0 (logxor #x80 (byte-ref byte-vector 0)))))
byte-vector)
;;@body
Given @1 modified by @code{ieee - byte - collate ! } , reverses the @1
;;modifications.
(define (ieee-byte-decollate! byte-vector)
(cond ((not (logtest #x80 (byte-ref byte-vector 0)))
(do ((idx (+ -1 (bytes-length byte-vector)) (+ -1 idx)))
((negative? idx))
(byte-set! byte-vector idx
(logxor #xFF (byte-ref byte-vector idx)))))
(else
(byte-set! byte-vector 0 (logxor #x80 (byte-ref byte-vector 0)))))
byte-vector)
;;@body
Returns copy of @1 encoded so that < ? } ordering of IEEE
;;floating-point byte-vectors matches numerical order.
(define (ieee-byte-collate byte-vector)
(ieee-byte-collate! (bytes-copy byte-vector)))
;;@body
Given @1 returned by @code{ieee - byte - collate } , reverses the @1
;;modifications.
(define (ieee-byte-decollate byte-vector)
(ieee-byte-decollate! (bytes-copy byte-vector)))
| null | https://raw.githubusercontent.com/evilbinary/scheme-lib/6df491c1f616929caa4e6569fa44e04df7a356a7/packages/slib/bytenumb.scm | scheme |
Permission to copy this software, to modify it, to redistribute it,
to distribute modified versions, and to use it for any purpose is
granted, subject to the following restrictions and understandings.
in full.
this software will be error-free, and I am under no obligation to
provide any services, by way of maintenance, update, or otherwise.
material, there shall be no use of my name in any advertising,
promotional, or sales literature without prior written consent in
each case.
@code{(require 'byte-number)}
@ftindex byte-number
@noindent
The multi-byte sequences produced and used by numeric conversion
routines are always big-endian. Endianness can be changed during
@code{write-bytes} @xref{Byte, read-bytes}.
@noindent
The sign of the length argument to bytes/integer conversion
procedures determines the signedness of the number.
@body
bytes are treated as two's-complement (can be negative).
@example
@end example
@body
Converts the integer @1 to a byte-array of @code{(abs @var{n})}
returned array are coded two's-complement.
@example
@end example
@body
S EEEEEEE E FFFFFFF FFFFFFFF FFFFFFFF
========= ========= ======== ========
0 1 8 9 31
@example
@end example
@body
S EEEEEEE EEEE FFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF
========= ========= ======== ======== ======== ======== ======== ========
@example
@end example
floating-point of @1.
@example
@end example
floating-point of @1.
@example
@result{} ( 0 0 0 0 0 0 0 1)
@end example
@noindent
the numerical ordering only when those numbers are non-negative.
@noindent
Straighforward modification of these formats can extend the
byte-collating order to work for their entire ranges. This
agreement enables the full range of numbers as keys in
@body
@1 and is its own functional inverse.
@body
ordering of two's-complement byte-vectors matches numerical order.
@body
@body
modifications.
@body
floating-point byte-vectors matches numerical order.
@body
modifications. | " bytenumb.scm " Byte integer and IEEE floating - point conversions .
Copyright ( C ) 2003
1 . Any copy made of this software must include this copyright notice
2 . I have made no warranty or representation that the operation of
3 . In conjunction with products arising from the use of this
(require 'byte)
(require 'logical)
reading and writing bytes using } and
Converts the first @code{(abs @var{n } ) } bytes of big - endian @1 array
to an integer . If @2 is negative then the integer coded by the
( bytes->integer ( bytes 0 0 0 15 ) -4 ) @result { } 15
( bytes->integer ( bytes 0 0 0 15 ) 4 ) @result { } 15
( bytes->integer ( bytes 255 255 255 255 ) -4 ) @result { } -1
( bytes->integer ( bytes 255 255 255 255 ) 4 ) @result { } 4294967295
( bytes->integer ( bytes 128 0 0 0 ) -4 ) @result { } -2147483648
( bytes->integer ( bytes 128 0 0 0 ) 4 ) @result { } 2147483648
(define (bytes->integer bytes n)
(define cnt (abs n))
(cond ((zero? n) 0)
((and (negative? n) (> (byte-ref bytes 0) 127))
(do ((lng (- 255 (byte-ref bytes 0))
(+ (- 255 (byte-ref bytes idx)) (* 256 lng)))
(idx 1 (+ 1 idx)))
((>= idx cnt) (- -1 lng))))
(else
(do ((lng (byte-ref bytes 0)
(+ (byte-ref bytes idx) (* 256 lng)))
(idx 1 (+ 1 idx)))
((>= idx cnt) lng)))))
bytes . If @1 and @2 are both negative , then the bytes in the
( bytes->list ( integer->bytes 15 -4 ) ) @result { } ( 0 0 0 15 )
( bytes->list ( integer->bytes 15 4 ) ) @result { } ( 0 0 0 15 )
( bytes->list ( integer->bytes -1 -4 ) ) @result { } ( 255 255 255 255 )
( bytes->list ( integer->bytes 4294967295 4 ) ) @result { } ( 255 255 255 255 )
( bytes->list ( integer->bytes -2147483648 -4 ) ) @result { } ( 128 0 0 0 )
( bytes->list ( integer->bytes 2147483648 4 ) ) @result { } ( 128 0 0 0 )
(define (integer->bytes n len)
(define bytes (make-bytes (abs len)))
(cond ((and (negative? n) (negative? len))
(do ((idx (+ -1 (abs len)) (+ -1 idx))
(res (- -1 n) (quotient res 256)))
((negative? idx) bytes)
(byte-set! bytes idx (- 255 (modulo res 256)))))
(else
(do ((idx (+ -1 (abs len)) (+ -1 idx))
(res n (quotient res 256)))
((negative? idx) bytes)
(byte-set! bytes idx (modulo res 256))))))
@1 must be a 4 - element byte - array . @0 calculates and returns the
value of @1 interpreted as a big - endian IEEE 4 - byte ( 32 - bit ) number .
(define (bytes->ieee-float bytes)
(define zero (or (string->number "0.0") 0))
(define one (or (string->number "1.0") 1))
(define len (bytes-length bytes))
(define S (logbit? 7 (byte-ref bytes 0)))
(define E (+ (ash (logand #x7F (byte-ref bytes 0)) 1)
(ash (logand #x80 (byte-ref bytes 1)) -7)))
(if (not (eqv? 4 len))
(slib:error 'bytes->ieee-float 'wrong 'length len))
(do ((F (byte-ref bytes (+ -1 len))
(+ (byte-ref bytes idx) (/ F 256)))
(idx (+ -2 len) (+ -1 idx)))
((<= idx 1)
(set! F (/ (+ (logand #x7F (byte-ref bytes 1)) (/ F 256)) 128))
(cond ((< 0 E 255) (* (if S (- one) one) (expt 2 (- E 127)) (+ 1 F)))
((zero? E)
(if (zero? F)
(if S (- zero) zero)
(* (if S (- one) one) (expt 2 -126) F)))
E must be 255
((not (zero? F)) (/ zero zero))
(else (/ (if S (- one) one) zero))))))
( - float ( bytes 0 0 0 0 ) ) @result { } 0.0
( - float ( bytes # x80 0 0 0 ) ) @result { } -0.0
( - float ( bytes # x40 0 0 0 ) ) @result { } 2.0
( - float ( bytes # x40 # xd0 0 0 ) ) @result { } 6.5
( - float ( bytes # xc0 # xd0 0 0 ) ) @result { } -6.5
( - float ( bytes 0 # x80 0 0 ) ) @result { } 11.754943508222875e-39
( - float ( bytes 0 # x40 0 0 ) ) @result { } 5.877471754111437e-39
( - float ( bytes 0 0 0 1 ) ) @result { } 1.401298464324817e-45
( - float ( bytes # xff # x80 0 0 ) ) @result { } -inf.0
( - float ( bytes # x7f # x80 0 0 ) ) @result { } + inf.0
( - float ( bytes # x7f # x80 0 1 ) ) @result { } 0/0
( - float ( bytes # x7f # xc0 0 0 ) ) @result { } 0/0
@1 must be a 8 - element byte - array . @0 calculates and returns the
value of @1 interpreted as a big - endian IEEE 8 - byte ( 64 - bit ) number .
(define (bytes->ieee-double bytes)
(define zero (or (string->number "0.0") 0))
(define one (or (string->number "1.0") 1))
(define len (bytes-length bytes))
(define S (logbit? 7 (byte-ref bytes 0)))
(define E (+ (ash (logand #x7F (byte-ref bytes 0)) 4)
(ash (logand #xF0 (byte-ref bytes 1)) -4)))
(if (not (eqv? 8 len))
(slib:error 'bytes->ieee-double 'wrong 'length len))
(do ((F (byte-ref bytes (+ -1 len))
(+ (byte-ref bytes idx) (/ F 256)))
(idx (+ -2 len) (+ -1 idx)))
((<= idx 1)
(set! F (/ (+ (logand #x0F (byte-ref bytes 1)) (/ F 256)) 16))
(cond ((< 0 E 2047) (* (if S (- one) one) (expt 2 (- E 1023)) (+ 1 F)))
((zero? E)
(if (zero? F)
(if S (- zero) zero)
(* (if S (- one) one) (expt 2 -1022) F)))
E must be 2047
((not (zero? F)) (/ zero zero))
(else (/ (if S (- one) one) zero))))))
0 1 11 12 63
( - double ( bytes 0 0 0 0 0 0 0 0 ) ) @result { } 0.0
( - double ( bytes # x80 0 0 0 0 0 0 0 ) ) @result { } -0.0
( - double ( bytes # x40 0 0 0 0 0 0 0 ) ) @result { } 2.0
( - double ( bytes # x40 # x1A 0 0 0 0 0 0 ) ) @result { } 6.5
( - double ( bytes # xC0 # x1A 0 0 0 0 0 0 ) ) @result { } -6.5
( - double ( bytes 0 8 0 0 0 0 0 0 ) ) @result { } 11.125369292536006e-309
( - double ( bytes 0 4 0 0 0 0 0 0 ) ) @result { } 5.562684646268003e-309
( - double ( bytes 0 0 0 0 0 0 0 1 ) ) @result { } 4.0e-324
( - double ( list->bytes ' ( 127 239 255 255 255 255 255 255 ) ) ) 179.76931348623157e306
( - double ( bytes # xFF # xF0 0 0 0 0 0 0 ) ) @result { } -inf.0
( - double ( bytes # x7F # xF0 0 0 0 0 0 0 ) ) @result { } + inf.0
( - double ( bytes # x7F # xF8 0 0 0 0 0 0 ) ) @result { } 0/0
@args x
Returns a 4 - element byte - array encoding the IEEE single - precision
(define ieee-float->bytes
(let ((exactify (if (provided? 'inexact) inexact->exact identity)))
(lambda (flt)
(define byts (make-bytes 4 0))
(define S (and (real? flt) (negative? (if (zero? flt) (/ flt) flt))))
(define (scale flt scl)
(cond ((zero? scl) (out (/ flt 2) scl))
((>= flt 16)
(let ((flt/16 (/ flt 16)))
(cond ((= flt/16 flt)
(byte-set! byts 0 (if S #xFF #x7F))
(byte-set! byts 1 #x80)
byts)
(else (scale flt/16 (+ scl 4))))))
((>= flt 2) (scale (/ flt 2) (+ scl 1)))
((and (>= scl 4)
(< (* 16 flt) 1)) (scale (* flt 16) (+ scl -4)))
((< flt 1) (scale (* flt 2) (+ scl -1)))
(else (out (+ -1 flt) scl))))
(define (out flt scl)
(do ((flt (* 128 flt) (* 256 (- flt val)))
(val (exactify (floor (* 128 flt)))
(exactify (floor (* 256 (- flt val)))))
(idx 1 (+ 1 idx)))
((> idx 3)
(byte-set! byts 1 (bitwise-if #x80 (ash scl 7) (byte-ref byts 1)))
(byte-set! byts 0 (+ (if S 128 0) (ash scl -1)))
byts)
(byte-set! byts idx val)))
(set! flt (magnitude flt))
(cond ((zero? flt) (if S (byte-set! byts 0 #x80)) byts)
((or (not (real? flt))
(not (= flt flt)))
(byte-set! byts 0 (if S #xFF #x7F))
(byte-set! byts 1 #xC0)
byts)
(else (scale flt 127))))))
( bytes->list ( - float->bytes 0.0 ) ) @result { } ( 0 0 0 0 )
( bytes->list ( ) ) @result { } ( 128 0 0 0 )
( bytes->list ( - float->bytes 2.0 ) ) @result { } ( 64 0 0 0 )
( bytes->list ( ieee - float->bytes 6.5 ) ) @result { } ( 64 208 0 0 )
( bytes->list ( -6.5 ) ) @result { } ( 192 208 0 0 )
( bytes->list ( - float->bytes 11.754943508222875e-39 ) ) @result { } ( 0 128 0 0 )
( bytes->list ( - float->bytes 5.877471754111438e-39 ) ) @result { } ( 0 64 0 0 )
( bytes->list ( - float->bytes 1.401298464324817e-45 ) ) @result { } ( 0 0 0 1 )
( bytes->list ( ieee - float->bytes -inf.0 ) ) @result { } ( 255 128 0 0 )
( bytes->list ( + inf.0 ) ) @result { } ( 127 128 0 0 )
( bytes->list ( ieee - float->bytes 0/0 ) ) @result { } ( 127 192 0 0 )
@args x
Returns a 8 - element byte - array encoding the IEEE double - precision
(define ieee-double->bytes
(let ((exactify (if (provided? 'inexact) inexact->exact identity)))
(lambda (flt)
(define byts (make-bytes 8 0))
(define S (and (real? flt) (negative? (if (zero? flt) (/ flt) flt))))
(define (scale flt scl)
(cond ((zero? scl) (out (/ flt 2) scl))
((>= flt 16)
(let ((flt/16 (/ flt 16)))
(cond ((= flt/16 flt)
(byte-set! byts 0 (if S #xFF #x7F))
(byte-set! byts 1 #xF0)
byts)
(else (scale flt/16 (+ scl 4))))))
((>= flt 2) (scale (/ flt 2) (+ scl 1)))
((and (>= scl 4)
(< (* 16 flt) 1)) (scale (* flt 16) (+ scl -4)))
((< flt 1) (scale (* flt 2) (+ scl -1)))
(else (out (+ -1 flt) scl))))
(define (out flt scl)
(do ((flt (* 16 flt) (* 256 (- flt val)))
(val (exactify (floor (* 16 flt)))
(exactify (floor (* 256 (- flt val)))))
(idx 1 (+ 1 idx)))
((> idx 7)
(byte-set! byts 1 (bitwise-if #xF0 (ash scl 4) (byte-ref byts 1)))
(byte-set! byts 0 (+ (if S 128 0) (ash scl -4)))
byts)
(byte-set! byts idx val)))
(set! flt (magnitude flt))
(cond ((zero? flt) (if S (byte-set! byts 0 #x80)) byts)
((or (not (real? flt))
(not (= flt flt)))
(byte-set! byts 0 #x7F)
(byte-set! byts 1 #xF8)
byts)
(else (scale flt 1023))))))
( bytes->list ( ieee - double->bytes 0.0 ) ) @result { } ( 0 0 0 0 0 0 0 0 )
( bytes->list ( ieee - double->bytes -0.0 ) ) @result { } ( 128 0 0 0 0 0 0 0 )
( bytes->list ( - double->bytes 2.0 ) ) @result { } ( 64 0 0 0 0 0 0 0 )
( bytes->list ( ieee - double->bytes 6.5 ) ) @result { } ( 64 26 0 0 0 0 0 0 )
( bytes->list ( - double->bytes -6.5 ) ) @result { } ( 192 26 0 0 0 0 0 0 )
( bytes->list ( - double->bytes 11.125369292536006e-309 ) )
@result { } ( 0 8 0 0 0 0 0 0 )
( bytes->list ( - double->bytes 5.562684646268003e-309 ) )
@result { } ( 0 4 0 0 0 0 0 0 )
( bytes->list ( ieee - double->bytes 4.0e-324 ) )
( bytes->list ( ieee - double->bytes -inf.0 ) ) @result { } ( 255 240 0 0 0 0 0 0 )
( bytes->list ( - double->bytes + inf.0 ) ) @result { } ( 127 240 0 0 0 0 0 0 )
( bytes->list ( - double->bytes 0/0 ) ) @result { } ( 127 248 0 0 0 0 0 0 )
Collation Order
The < ? } ordering of big - endian byte - array
representations of fixed and IEEE floating - point numbers agrees with
- sequential - access - method } databases .
Modifies sign bit of @1 so that < ? } ordering of
two's - complement byte - vectors matches numerical order . @0 returns
(define (integer-byte-collate! byte-vector)
(byte-set! byte-vector 0 (logxor #x80 (byte-ref byte-vector 0)))
byte-vector)
Returns copy of @1 with sign bit modified so that < ? }
@0 is its own functional inverse .
(define (integer-byte-collate byte-vector)
(integer-byte-collate! (bytes-copy byte-vector)))
Modifies @1 so that < ? } ordering of IEEE floating - point
byte - vectors matches numerical order . @0 returns @1 .
(define (ieee-byte-collate! byte-vector)
(cond ((logtest #x80 (byte-ref byte-vector 0))
(do ((idx (+ -1 (bytes-length byte-vector)) (+ -1 idx)))
((negative? idx))
(byte-set! byte-vector idx
(logxor #xFF (byte-ref byte-vector idx)))))
(else
(byte-set! byte-vector 0 (logxor #x80 (byte-ref byte-vector 0)))))
byte-vector)
Given @1 modified by @code{ieee - byte - collate ! } , reverses the @1
(define (ieee-byte-decollate! byte-vector)
(cond ((not (logtest #x80 (byte-ref byte-vector 0)))
(do ((idx (+ -1 (bytes-length byte-vector)) (+ -1 idx)))
((negative? idx))
(byte-set! byte-vector idx
(logxor #xFF (byte-ref byte-vector idx)))))
(else
(byte-set! byte-vector 0 (logxor #x80 (byte-ref byte-vector 0)))))
byte-vector)
Returns copy of @1 encoded so that < ? } ordering of IEEE
(define (ieee-byte-collate byte-vector)
(ieee-byte-collate! (bytes-copy byte-vector)))
Given @1 returned by @code{ieee - byte - collate } , reverses the @1
(define (ieee-byte-decollate byte-vector)
(ieee-byte-decollate! (bytes-copy byte-vector)))
|
82d07f81a60ba6e95142cc30c769388f30f43658463bb7b76228e730f1655a67 | quil-lang/quilc | stabilizer.lisp | ;;;; stabilizer.lisp
;;;;
Authors : ,
(in-package #:cl-quil.clifford)
;;; Most of this is from or inspired by -ph/0406196.pdf
;;;
;;; Gottesman's paper is also helpful
;;; -ph/9807006.pdf ...but BEWARE HIS PIQUANT
;;; QUBIT NOTATION!! Correct qubit ordering is very important. Pay
;;; attention to which qubits are least/most significant and how they
;;; are ordered in the code with respect to this!!
(deftype tableau-index ()
'(integer 0 (#.array-total-size-limit)))
(deftype tableau ()
In all , this is a ( 2N + 1 ) x ( 2N + 1 ) square matrix of bits .
;;
;; Rows 0 to N - 1 are "destabilizer generators"
Rows N to 2N - 1 are " stabilizer generators "
Row 2N is for scratch space , as suggested by the et al . paper .
;;
Columns 0 to N are factors ( x_i )
Columns N to 2N - 1 are factors ( z_i )
;; Column 2N are the phases r
'(simple-array bit (* *)))
(defun make-blank-tableau (n)
(check-type n (integer 1))
(let ((size (1+ (* 2 n))))
(make-array (list size size) :element-type 'bit
:initial-element 0)))
(defun copy-tableau (tab)
"Creates a copy of TAB and returns it."
(let ((copy (make-tableau-zero-state (tableau-qubits tab))))
(loop :for i :below (array-total-size copy)
:do (setf (row-major-aref copy i)
(row-major-aref tab i)))
copy))
(declaim (inline tableau-qubits
tableau-x (setf tableau-x)
tableau-z (setf tableau-z)
tableau-r (setf tableau-r)
tableau-scratch (setf tableau-scratch)))
(defun tableau-qubits (tab)
"How many qubits does the tableau TAB represent?"
(declare (type tableau tab))
(the tableau-index (ash (1- (array-dimension tab 0)) -1)))
(defun tableau-x (tab i j)
(declare (type tableau tab)
(type tableau-index i j))
(aref tab i j))
(defun (setf tableau-x) (new-bit tab i j)
(declare (type tableau tab)
(type tableau-index i j)
(type bit new-bit))
(setf (aref tab i j) new-bit))
(defun tableau-z (tab i j)
(declare (type tableau tab)
(type tableau-index i j))
(aref tab i (+ j (tableau-qubits tab))))
(defun (setf tableau-z) (new-bit tab i j)
(declare (type tableau tab)
(type tableau-index i j)
(type bit new-bit))
(setf (aref tab i (+ j (tableau-qubits tab))) new-bit))
(defun tableau-r (tab i)
(declare (type tableau tab)
(type tableau-index i))
(aref tab i (* 2 (tableau-qubits tab))))
(defun (setf tableau-r) (new-bit tab i)
(declare (type tableau tab)
(type tableau-index i)
(type bit new-bit))
(setf (aref tab i (* 2 (tableau-qubits tab))) new-bit))
(defun tableau-scratch (tab i)
(declare (type tableau tab)
(type tableau-index i))
(aref tab (* 2 (tableau-qubits tab)) i))
(defun (setf tableau-scratch) (new-bit tab i)
(declare (type tableau tab)
(type tableau-index i)
(type bit new-bit))
(setf (aref tab (* 2 (tableau-qubits tab)) i) new-bit))
(defun tableau-clear-scratch (tab)
"Clear the scratch row of TAB."
(dotimes (i (1+ (* 2 (tableau-qubits tab))))
(setf (tableau-scratch tab i) 0)))
(defun display-row (tab i)
(cond
((= 1 (tableau-r tab i))
(write-string "-"))
(t
(write-string "+")))
(loop :for j :below (tableau-qubits tab) :do
(let ((x (tableau-x tab i j))
(z (tableau-z tab i j)))
(cond
((and (= 0 x) (= 0 z)) (write-string "I"))
((and (= 1 x) (= 0 z)) (write-string "X"))
((and (= 0 x) (= 1 z)) (write-string "Z"))
((and (= 1 x) (= 1 z)) (write-string "Y"))))))
(defun tableau-copy-row (tab i k)
"Given a tableau TAB, overwrite row I with row K."
(declare (type tableau tab)
(type tableau-index i k))
;; set row i to row k
(dotimes (j (array-dimension tab 1))
(setf (aref tab i j) (aref tab k j))))
(defun tableau-swap-row (tab i k)
"Given a tableau TAB, swap row I with row K."
(declare (type tableau tab)
(type tableau-index i k))
(dotimes (j (1+ (* 2 (tableau-qubits tab))))
(rotatef (aref tab i j) (aref tab k j))))
(defun display-tableau (tab)
"Display the tableau TAB a la Aaronson's CHP program."
(let ((n (tableau-qubits tab)))
(loop :for i :below (* 2 n) :do
(display-row tab i)
(terpri)
(when (= n (1+ i))
(loop :repeat (1+ n) :do
(write-char #\-))
(terpri)))))
(defun zero-out-tableau (tab)
"Bring the tableau to the zero state."
(dotimes (i (array-total-size tab))
(setf (row-major-aref tab i) 0))
(dotimes (i (* 2 (tableau-qubits tab)))
(setf (aref tab i i) 1)))
(defun make-tableau-zero-state (n)
"Create a tableau of N qubits in the zero state."
(let ((zero (make-blank-tableau n)))
(dotimes (i (* 2 n) zero)
(setf (aref zero i i) 1))))
(defun take-tableau-to-basis-state (tab x)
"Bring the tableau to the specific basis state X. X is an integer interpreted as a collection of bits, so for example, |01000> = #b01000 = 8."
(assert (>= (tableau-qubits tab) (integer-length x)))
(let ((n (tableau-qubits tab)))
(zero-out-tableau tab)
(dotimes (i n)
(when (logbitp i x)
(setf (tableau-r tab (+ i n)) 1)))))
(declaim (inline phase-of-product))
(defun phase-of-product (x1 z1 x2 z2)
This function is called " g " in the et al . paper .
(declare (type bit x1 z1 x2 z2))
(levi-civita (logior x1 (ash z1 1))
(logior x2 (ash z2 1))))
(declaim (inline %band b* %bior bmax %bxor b+ bnot))
(defun %band (a b)
(declare (type bit a b))
(the bit (logand a b)))
(defun b* (&rest bits)
(declare (dynamic-extent bits))
(let ((result 1))
(declare (type bit result))
(dolist (bit bits result)
(setf result (%band result bit)))))
(defun %bior (a b)
(declare (type bit a b))
(the bit (logior a b)))
(defun bmax (&rest bits)
(declare (dynamic-extent bits))
(let ((result 0))
(declare (type bit result))
(dolist (bit bits result)
(setf result (%bior result bit)))))
(defun %bxor (a b)
(declare (type bit a b))
(the bit (logxor a b)))
(defun b+ (&rest bits)
(declare (dynamic-extent bits))
(let ((result 0))
(declare (type bit result))
(dolist (bit bits result)
(setf result (%bxor result bit)))))
(defun bnot (b)
(declare (type bit b))
(the bit (- 1 b)))
(define-modify-macro xorf (x) %bxor)
(defun incurred-phase-from-row-product (tab h i)
"Calculate the incurred phase by multiplying row H and row I together."
(mod (+ (* 2 (tableau-r tab h))
(* 2 (tableau-r tab i))
(loop :with sum :of-type fixnum := 0
:for j :below (tableau-qubits tab)
:for ph := (phase-of-product
(tableau-x tab i j)
(tableau-z tab i j)
(tableau-x tab h j)
(tableau-z tab h j))
:do (incf sum ph)
:finally (return sum)))
4))
(declaim (inline row-product))
(defun row-product (tab h i &key allow-dirty-phase)
"Set generator h to h + i, where + is the Pauli group operation. When ALLOW-DIRTY-PHASE is true, phases are allowed to be i or -i."
;; We do this because while we are multiplying rows around to
;; generate the full stabilizer group, even though each stabilizer
will eventually have a phase of 1 or -1 , the phase may take the
;; value of i or -i in intermediate steps (see below).
(let ((sum (incurred-phase-from-row-product tab h i)))
Step 1
(cond
((= 0 sum) (setf (tableau-r tab h) 0))
((= 2 sum) (setf (tableau-r tab h) 1))
((not allow-dirty-phase)
(error "invalid prod between row ~D and ~D (got ~D, which is an invalid phase for a generator or antigenerator!):~%~A~%~A~%" h i sum
(with-output-to-string (*standard-output*)
(display-row tab h))
(with-output-to-string (*standard-output*)
(display-row tab i)))))
Step 2
(dotimes (j (tableau-qubits tab))
(xorf (tableau-x tab h j) (tableau-x tab i j))
(xorf (tableau-z tab h j) (tableau-z tab i j)))
;; Return the phase
sum))
;;; (Explained above in row-product, but re-explained here) While we
;;; are multiplying rows into the scratch row to generate the full
;;; stabilizer group, even though each stabilizer will eventually have
a phase of 1 or -1 , the phase may take the value of i or -i in
;;; intermediate steps. This function multiplies a row i into the
;;; scratch row, and returns the phase produced by the multiplication
( can be 1 , i , -1 , or -i ) .
(defun multiply-into-scratch (tab i)
"Multiplies row I of TAB into the scratch row, and return the phase produced by the multiplication (as 0, 1, 2, 3 for 1, i, -1, -i respectively)."
(declare (notinline row-product))
(let ((n (tableau-qubits tab)))
(prog1 (row-product tab (* 2 n) i :allow-dirty-phase t)
;; This function should only be used where phase is tracked separately.
(setf (tableau-r tab (* 2 n)) 0))))
;;; This is intended to be a helper function for
;;; COMPILE-TABLEAU-OPERATION. Look at that function to see if it
;;; helps understanding this one.
(defun clifford-stabilizer-action (c)
"Compute a symbolic representation of the action of the Clifford element C on the stabilizer representation of a state, namely the \"tableau representation\".
Given a Clifford C, calculate two values:
1. A list of variable names representing X-Z pairs on qubits 0, 1, .... A typical value will look like
(X0 Z0 X1 Z1 ... Xn Zn),
but the symbols may be uninterned or named differently.
2. A list of updates to the variables of (1), represented as Boolean expressions. Similarly to (2), these are expressions in 1-1 correspondence with (1) which, if evaluated, would produce the updates to said variables.
Note that no expressions calculating the phase update are created. This is because these phase updates are calculated by the function generate-clifford-image-phase instead."
(let* ((num-qubits (clifford-num-qubits c))
(num-variables (* 2 num-qubits))
(variables (loop :for i :below num-variables
:collect (if (evenp i)
(alexandria:format-symbol nil "X~D" (floor i 2))
(alexandria:format-symbol nil "Z~D" (floor i 2)))))
(new-variables (make-array num-variables :initial-element nil)))
We will be mapping over all operating on a single
qubit . We will compute the action on the and use this to
;; produce part of the action.
(map-all-paulis num-qubits
(lambda (i p)
(let* ((cp (apply-clifford c p)))
When is a generator ( i.e. , X or
;; Z), then we want to record which other
;; variables see an effect from this generator
under C. Similarly to the last loop , we
;; loop over the bitwise representation of the
Pauli _ acted on by the _ ( CP
;; instead of P). When we find any bit, we
;; record the X or Z variable in that bit's
;; running list. In the end, the running list
;; represents a disjunction of contributions.
X and Z 's will have power of two indexes .
(let ((var (nth (1- (integer-length i)) variables)))
;; The var that contributes to X- and Z-FACTORS
(loop :with bits := (pauli-index cp)
:for i :below num-variables
: when (= 1 ( ldb ( byte 1 0 ) bits ) ) ; . to ODDP
;; :do (push var (aref new-variables i))
:do (push (if (= 1 (ldb (byte 1 0) bits)) var 0) (aref new-variables i)) (setf bits (ash bits -1))))))))
;; We didn't actually construct the disjunction yet out of the
;; running lists, so do that here.
(map-into new-variables (lambda (sum) `(b+ ,@sum)) new-variables)
;; Return the values.
(values
variables
(coerce new-variables 'list))))
Many moons ago ( 04/2019 ) , the phase updates produced by a acting on
;;; a tableau via compile-tableau-operation (and
;;; clifford-stabilizer-action) were slightly incorrect. Before, phases
were updated based on values in the un - clifforded tableau , but in
;;; reality, phase updates are dependent on the _updated_ X and Z bits
;;; of the tableau.
;;;
;;; This function calculates the correct phase update to each
;;; generator and antigenerator of a tableau acted on by a clifford.
It does this ( with a minor adjustment or two ) by :
;;;
;;; 1) Considering the row (generator/antigenerator) as a sequence
;;; of single-qubit X and Z paulis.
;;;
2 ) Mapping each of these paulis to their image under ,
;;; storing these new, more complicated paulis in contributing-ops.
;;;
;;; 3) Multiplying all these mapped paulis together to find the
image of the entire tableau row under the .
;;;
;;; This tableau row image will now have an associated phase with it
;;; (which is a multiple of i). The minor adjustments refer to this
;;; detail: if the tableau row already has any Y paulis prior to the
;;; clifford action, the final phase value will have to be increased by
1 for each Y. This is because in the original row , the -i factor
that comes from XZ = -iY is adjusted to 0 , so we need to do the
;;; same for the resulting phase. Otherwise, a clifford that maps Y to
;;; Y, for example, would represent Y as X * Z, map them to themselves,
;;; multiply them together, and find that Y maps to -iY.
(defun generate-clifford-image-phase (tab-var c row-var qubit-vars)
"Calculate the phase update to a specific row in the tableau TAB, when acted on by a clifford C on specific qubits."
(let* ((cn (num-qubits c))
(images (clifford-basis-map c)))
(alexandria:with-gensyms (row-image y-phase-offset Xq Zq Yq)
`(let ((,row-image (make-components ,cn))
(,y-phase-offset 0))
(declare (type fixnum ,y-phase-offset)
(type pauli-components ,row-image))
,@(loop :for i :below (length qubit-vars)
:for q :in (reverse qubit-vars)
:collect `(let* ((,Xq (tableau-x ,tab-var ,row-var ,q))
(,Zq (tableau-z ,tab-var ,row-var ,q))
(,Yq (logand ,Xq ,Zq)))
(declare (type bit ,Xq ,Yq ,Zq))
(when (= 1 ,Xq) (multiply-components-into ,row-image ,(pauli-components (aref images (* 2 i))) ,row-image))
(when (= 1 ,Zq) (multiply-components-into ,row-image ,(pauli-components (aref images (1+ (* 2 i)))) ,row-image))
(incf ,y-phase-offset ,Yq)))
(floor (mod (the fixnum (+ ,y-phase-offset (aref ,row-image 0))) 4) 2)))))
(defun compile-tableau-operation (c)
"Compile a Clifford element into a tableau operation. This will be a lambda form whose first argument is the tableau to operate on, and whose remaining arguments are the qubit indexes to operate on. Upon applying this function to a tableau, it will be mutated "
(check-type c clifford)
(let* ((num-qubits (num-qubits c))
(i (gensym "I-"))
(tab (gensym "TAB-"))
(qubits (loop :for i :below num-qubits
:collect (alexandria:format-symbol nil "Q~D" (- num-qubits 1 i)))))
(multiple-value-bind (variables new-variables)
(clifford-stabilizer-action c)
;; Most of this lambda can be understood by understanding the
return values of CLIFFORD - STABILIZER - ACTION . See the
;; documentation of that function.
`(lambda (,tab ,@qubits)
(declare (optimize speed (safety 0) (debug 0) (space 0) (compilation-speed 0))
(type tableau ,tab)
(type tableau-index ,@qubits))
(dotimes (,i (* 2 (tableau-qubits ,tab)))
(declare (type tableau-index ,i))
First , we construct bindings to these variables
;; according to the qubits we are operating on.
(let (,@(loop :for qubit :in (reverse qubits)
:for (x z) :on variables :by #'cddr
:collect `(,x (tableau-x ,tab ,i ,qubit))
:collect `(,z (tableau-z ,tab ,i ,qubit))))
(declare (type bit ,@variables))
;; Calculate the new phase.
(xorf (tableau-r ,tab ,i) ,(generate-clifford-image-phase tab c i qubits))
;; Update the tableau with the new values.
(setf
,@(loop :for qubit :in (reverse qubits)
:for (x z) :on new-variables :by #'cddr
;; Set this...
:collect `(tableau-x ,tab ,i ,qubit)
;; ...to this...
:collect x
;; And set this...
:collect `(tableau-z ,tab ,i ,qubit)
;; to this...
:collect z))))))))
(defun tableau-function (c)
"Given a Clifford C, return a function representing its action on a tableau."
(compile nil (compile-tableau-operation c)))
These functions : TABLEAU - APPLY-{CNOT , H , PHASE } are hard - coded
from the et al . paper . These can be readily generated
;;; from the above procedure.
(defun tableau-apply-cnot (tab a b)
(declare (type tableau tab)
(type tableau-index a b))
(dotimes (i (* 2 (tableau-qubits tab)))
(xorf (tableau-r tab i) (logand (tableau-x tab i a)
(tableau-z tab i b)
(logxor 1
(tableau-x tab i b)
(tableau-z tab i a))))
(xorf (tableau-x tab i b) (tableau-x tab i a))
(xorf (tableau-z tab i a) (tableau-z tab i b))))
(defun tableau-apply-h (tab q)
(declare (type tableau tab)
(type tableau-index q))
(dotimes (i (* 2 (tableau-qubits tab)))
(xorf (tableau-r tab i) (logand (tableau-x tab i q) (tableau-z tab i q)))
(rotatef (tableau-x tab i q) (tableau-z tab i q))))
(defun tableau-apply-phase (tab q)
(declare (type tableau tab)
(type tableau-index q))
(dotimes (i (* 2 (tableau-qubits tab)))
(xorf (tableau-r tab i) (logand (tableau-x tab i q) (tableau-z tab i q)))
(xorf (tableau-z tab i q) (tableau-x tab i q))))
(declaim (inline tableau-set-row-to-pauli tableau-copy-row))
(defun tableau-set-row-to-pauli (tab i b)
"Given a tableau TAB, set row I to be the single qubit Pauli term B, where if 0 <= B < N, the X_B will be set, and if N <= B < 2*N, then Z_(B - N) will be set."
(declare (type tableau tab)
(type tableau-index i b))
(dotimes (j (array-dimension tab 1))
(setf (aref tab i j) 0))
(setf (aref tab i b) 1)
nil)
: For some reason that I 'm not sure about , the procedure for
non - deterministic measurement from the et al . paper
;;; didn't work. I had to look at their C code for inspiration, which
;;; oddly does work (and doesn't seem to do precisely what the paper
;;; says.)
;;;
The general idea is a two step operation : ( 1 ) determine if the
measurement would produce a deterministic result , ( 2 ) determine
;;; the result.
(defun tableau-measure (tab q)
(declare (optimize speed (safety 0) (debug 0) (space 0) (compilation-speed 0))
(type tableau tab)
(type tableau-index q))
;; return measurement outcome, and boolean indicating if it was
;; deterministic
(let* ((n (tableau-qubits tab))
(p (loop :for p :below n
;; Look at the stabilizer generators, hence the + N.
:when (= 1 (tableau-x tab (+ p n) q))
:do (return p)
:finally (return nil))))
(declare (type (or tableau-index null) p)
(type tableau-index n))
;; The value of P is a reference to the Pth stabilizer
;; generator such that a Pauli X_q is present.
(cond
;; Case I: Outcome is not deterministic.
(p
(tableau-copy-row tab p (+ p n))
(tableau-set-row-to-pauli tab (+ p n) (+ q n))
(setf (tableau-r tab (+ p n)) (random 2))
(dotimes (i (* 2 n))
(when (and (/= i p)
(= 1 (tableau-x tab i q)))
(row-product tab i p)))
(values (tableau-r tab (+ p n)) nil))
;; Case II: Outcome is determined.
;;
;; The work below will not modify the tableau (except for the
;; scratch space). This is used simply to compute what the
;; measurement would be.
(t
Zero out the scratch space .
(tableau-clear-scratch tab)
(let ((m (loop :for m :below n
:when (= 1 (tableau-x tab m q))
:do (return m)
:finally (return n))))
(tableau-copy-row tab (* 2 n) (+ m n))
(loop :for i :from (1+ m) :below n :do
(when (= 1 (tableau-x tab i q))
(row-product tab (* 2 n) (+ i n))))
(values (tableau-r tab (* 2 n)) t))))))
(defun put-tableau-into-row-echelon-form (tab)
"Perform Gaussian elimination to put the tableau in row echelon form. Specifically, the modified generators will be put in the form
|1 * * * * * * * * * * *|
|. 1 * * * * * * * * * *|
|. . . 1 * * * * * * * *|
|. . . . . 1 * * * * * *|
|. . 0 . . . . 1 * * * *|
|. . . . . . . . 1 * * *|
^-----X----^ ^----Z-----^
The upper generators comprise only X's and Y's while the lower generators comprise only Z's. This makes it easy to
1) Determine how many nonzero basis states are present, based on the number of purely X/Y generators (which = log(# of nonzero basis states))
2) Easily find a nonzero basis state using the purely Z generators (done in the find-nonzero-operator function below).
Returns the number of purely X/Y generators.
"
(let* ((n (tableau-qubits tab))
(curr-row n))
(flet ((elim-generator (gen-type)
(dotimes (column n)
;; Find a generator of gen-type in this column
(let ((gen-row (loop :for gen-row :from curr-row :below (* 2 n)
:when (= 1 (funcall gen-type tab gen-row column))
:do (return gen-row)
:finally (return nil))))
;; Swap this generator up, and eliminate gen-type generators in this column from all other rows
(unless (null gen-row)
(tableau-swap-row tab curr-row gen-row)
(tableau-swap-row tab (- curr-row n) (- gen-row n))
(loop :for elim-row :from (1+ curr-row) :below (* 2 n)
;; When there is a generator of gen-type in this column of elim-row...
:when (= 1 (funcall gen-type tab elim-row column))
;; !!ELIMINATE!!
:do (row-product tab elim-row curr-row)
(row-product tab (- curr-row n) (- elim-row n)))
(incf curr-row))))))
Eliminate X 's to get upper generators ( X / Y only )
(elim-generator #'tableau-x)
;; The number of rows we've used to eliminate is the log of how
;; many nonzero basis states we have. This is because the states
;; generated by these X/Y generators cannot destructively
;; interfere with each other: they each flip an unique bit.
(prog1 (- curr-row n)
Eliminate Z 's to get lower generators ( Z only )
(elim-generator #'tableau-z)))))
;;; The general procedure of extracting the wavefunction from the
;;; tableau is just generating all of the state's stabilizers (and
;;; applying them to some state). However, this state has to be chosen
;;; carefully, since it's possible that the stabilizer operator sum
;;; will cause everything to destructively interfere and return nothing
;;; (not the |0...0> state, literally nothing, as if the state is in
;;; the "nullspace" of the stabilizer sum). This function ensures we
;;; have a good state to operate on that gives us the correct
;;; stabilizer state.
(defun find-nonzero-operator (tab)
"Given a tableau TAB, find a Pauli operator P such that P|0...0> has nonzero amplitude in the state represented by TAB. Write this operator to the scratch space of TAB. This function also puts TAB into REF (row echelon form), since P is found using the purely Z generators."
(let ((n (tableau-qubits tab))
(log-nonzero (put-tableau-into-row-echelon-form tab)))
Zero out scratch space
(tableau-clear-scratch tab)
;; For each row, starting from the bottom of the Z generators
(loop :for row :from (1- (* 2 n)) :downto (+ n log-nonzero)
:do (let ((phase (tableau-r tab row))
(first-z n))
;; Find the leftmost Z in this generator
(loop :for j :from (1- n) :downto 0
:when (= 1 (tableau-z tab row j))
:do (setf first-z j)
(when (= 1 (tableau-scratch tab j))
(xorf phase 1)))
Change the corresponding X in the P operator as necessary
(when (= phase 1)
(xorf (tableau-scratch tab first-z) 1))))))
(defun read-basis-state-from-scratch-row (tab)
"Given a tableau TAB, read off the operator on the scratch row as a basis state. Returns two values:
1) the basis state as an integer
2) the phase of the state as an integer."
(let* ((n (tableau-qubits tab))
(state 0)
(phase 0))
(dotimes (i n)
(when (= 1 (tableau-x tab (* 2 n) i))
(incf state (expt 2 i))
(when (= 1 (tableau-z tab (* 2 n) i))
(incf phase))))
(values state phase)))
The two nested dotimes in this function are a little mysterious ,
;;; but they are just a way to cleverly loop over all possible
;;; combinations of generators.
(defun tableau-wavefunction (tab)
"Given a tableau TAB, generate and return the wavefunction representation of the stabilizer state the tableau represents, using the normalized sum of all stabilizers.
Note: the scratch space is used as an area to write intermediate state values, and starts with the operator returned by find-nonzero-operator."
(let* ((n (tableau-qubits tab))
(log-nonzero (put-tableau-into-row-echelon-form tab))
(norm (sqrt (expt 2 log-nonzero)))
(wf (make-array (expt 2 n) :element-type '(complex double-float) :initial-element #C(0.0d0 0.0d0)))
(running-phase 0))
(find-nonzero-operator tab)
(dotimes (i (expt 2 log-nonzero))
(let ((x (logxor i (1+ i))))
(dotimes (j log-nonzero)
(when (logbitp j x)
(incf running-phase (multiply-into-scratch tab (+ n j)))))
(multiple-value-bind (state read-phase) (read-basis-state-from-scratch-row tab)
(setf (aref wf state) (/ (expt #C(0.0d0 1.0d0) (+ read-phase running-phase)) norm)))))
wf))
The .chp file format is an input to 's chp program written
in is a parser and interpreter for it .
(defun interpret-chp (code tab &key silent)
(let ((*standard-output* (if silent (make-broadcast-stream) *standard-output*)))
(loop :for i :from 1
:for isn :in code
:do
(format t "~D: ~A" i isn)
(alexandria:destructuring-ecase isn
((H q) (tableau-apply-h tab q))
((S q) (tableau-apply-phase tab q))
((CNOT p q) (tableau-apply-cnot tab p q))
((MEASURE q) (multiple-value-bind (outcome determ?)
(tableau-measure tab q)
(format t " => ~D~:[ (random)~;~]" outcome determ?))))
(terpri))))
(defun read-chp-file (file)
"Parse a .chp file as defined by Aaronson."
(let ((max-qubit 0))
(labels ((parse-gate (gate-name)
(cond
((string= gate-name "h") 'H)
((string= gate-name "c") 'CNOT)
((string= gate-name "p") 'S)
((string= gate-name "m") 'MEASURE)
(t (error "Invalid gate name: ~S" gate-name))))
(parse-qubits (qubits)
(loop :with seen := 0
:for qubit-string :in qubits
:for qubit := (parse-integer qubit-string :junk-allowed nil)
:collect (progn
(when (minusp qubit)
(error "Qubits must be non-negative integers"))
(when (logbitp qubit seen)
(error "Can't have duplicate qubits: ~A" qubits))
(setf seen (dpb 1 (byte 1 qubit) seen))
(setf max-qubit (max max-qubit qubit))
qubit)))
(parse-line (line)
(let ((split (split-sequence:split-sequence #\Space line :remove-empty-subseqs t)))
(cond
((null split)
nil)
(t
(destructuring-bind (gate . qubits) split
(when (null qubits)
(error "Invalid line, need qubits: ~S" line))
(cons (parse-gate gate) (parse-qubits qubits))))))))
(with-open-file (s file :direction ':input)
;; Read until the # line
(loop :for line := (read-line s nil ':eof)
:do (cond
((eq ':eof line) (error "Didn't find a # line"))
;; We can start processing lines.
((string= line "#") (loop-finish))))
;; Read the actual gate lines.
(values (loop :for line := (read-line s nil ':eof)
:until (eq ':eof line)
:for parsed-line := (parse-line line)
:when parsed-line
:collect parsed-line)
(1+ max-qubit))))))
(defun interpret-chp-file (file)
"Execute one of Aaronson's .chp files."
(multiple-value-bind (code num-qubits)
(read-chp-file file)
(let ((tab (make-tableau-zero-state num-qubits)))
(interpret-chp code tab))))
(defun random-chp-and-quil (q n)
"Generates a random CHP circuit on q qubits, of n gates.
Outputs two values:
1) The parsed CHP format of the random circuit
2) The equivalent random circuit in quil.
Intended for testing purposes."
(let ((quil-str (make-string-output-stream)))
(values
(loop :repeat n
:for q1 := (random q)
:for q2 := (mod (+ q1 (1+ (random (1- q)))) q)
:for chp-gate := (alexandria:whichever
`(H ,q1)
`(S ,q1)
`(CNOT ,q1 ,q2))
:for quil-gate := (format nil "~{~A~^ ~}" chp-gate)
:collect chp-gate
:do (write-line quil-gate quil-str))
(get-output-stream-string quil-str))))
| null | https://raw.githubusercontent.com/quil-lang/quilc/3f3260aaa65cdde25a4f9c0027959e37ceef9d64/src/clifford/stabilizer.lisp | lisp | stabilizer.lisp
Most of this is from or inspired by -ph/0406196.pdf
Gottesman's paper is also helpful
-ph/9807006.pdf ...but BEWARE HIS PIQUANT
QUBIT NOTATION!! Correct qubit ordering is very important. Pay
attention to which qubits are least/most significant and how they
are ordered in the code with respect to this!!
Rows 0 to N - 1 are "destabilizer generators"
Column 2N are the phases r
set row i to row k
We do this because while we are multiplying rows around to
generate the full stabilizer group, even though each stabilizer
value of i or -i in intermediate steps (see below).
Return the phase
(Explained above in row-product, but re-explained here) While we
are multiplying rows into the scratch row to generate the full
stabilizer group, even though each stabilizer will eventually have
intermediate steps. This function multiplies a row i into the
scratch row, and returns the phase produced by the multiplication
This function should only be used where phase is tracked separately.
This is intended to be a helper function for
COMPILE-TABLEAU-OPERATION. Look at that function to see if it
helps understanding this one.
produce part of the action.
Z), then we want to record which other
variables see an effect from this generator
loop over the bitwise representation of the
instead of P). When we find any bit, we
record the X or Z variable in that bit's
running list. In the end, the running list
represents a disjunction of contributions.
The var that contributes to X- and Z-FACTORS
. to ODDP
:do (push var (aref new-variables i))
We didn't actually construct the disjunction yet out of the
running lists, so do that here.
Return the values.
a tableau via compile-tableau-operation (and
clifford-stabilizer-action) were slightly incorrect. Before, phases
reality, phase updates are dependent on the _updated_ X and Z bits
of the tableau.
This function calculates the correct phase update to each
generator and antigenerator of a tableau acted on by a clifford.
1) Considering the row (generator/antigenerator) as a sequence
of single-qubit X and Z paulis.
storing these new, more complicated paulis in contributing-ops.
3) Multiplying all these mapped paulis together to find the
This tableau row image will now have an associated phase with it
(which is a multiple of i). The minor adjustments refer to this
detail: if the tableau row already has any Y paulis prior to the
clifford action, the final phase value will have to be increased by
same for the resulting phase. Otherwise, a clifford that maps Y to
Y, for example, would represent Y as X * Z, map them to themselves,
multiply them together, and find that Y maps to -iY.
Most of this lambda can be understood by understanding the
documentation of that function.
according to the qubits we are operating on.
Calculate the new phase.
Update the tableau with the new values.
Set this...
...to this...
And set this...
to this...
from the above procedure.
didn't work. I had to look at their C code for inspiration, which
oddly does work (and doesn't seem to do precisely what the paper
says.)
the result.
return measurement outcome, and boolean indicating if it was
deterministic
Look at the stabilizer generators, hence the + N.
The value of P is a reference to the Pth stabilizer
generator such that a Pauli X_q is present.
Case I: Outcome is not deterministic.
Case II: Outcome is determined.
The work below will not modify the tableau (except for the
scratch space). This is used simply to compute what the
measurement would be.
Find a generator of gen-type in this column
Swap this generator up, and eliminate gen-type generators in this column from all other rows
When there is a generator of gen-type in this column of elim-row...
!!ELIMINATE!!
The number of rows we've used to eliminate is the log of how
many nonzero basis states we have. This is because the states
generated by these X/Y generators cannot destructively
interfere with each other: they each flip an unique bit.
The general procedure of extracting the wavefunction from the
tableau is just generating all of the state's stabilizers (and
applying them to some state). However, this state has to be chosen
carefully, since it's possible that the stabilizer operator sum
will cause everything to destructively interfere and return nothing
(not the |0...0> state, literally nothing, as if the state is in
the "nullspace" of the stabilizer sum). This function ensures we
have a good state to operate on that gives us the correct
stabilizer state.
For each row, starting from the bottom of the Z generators
Find the leftmost Z in this generator
but they are just a way to cleverly loop over all possible
combinations of generators.
Read until the # line
We can start processing lines.
Read the actual gate lines. | Authors : ,
(in-package #:cl-quil.clifford)
(deftype tableau-index ()
'(integer 0 (#.array-total-size-limit)))
(deftype tableau ()
In all , this is a ( 2N + 1 ) x ( 2N + 1 ) square matrix of bits .
Rows N to 2N - 1 are " stabilizer generators "
Row 2N is for scratch space , as suggested by the et al . paper .
Columns 0 to N are factors ( x_i )
Columns N to 2N - 1 are factors ( z_i )
'(simple-array bit (* *)))
(defun make-blank-tableau (n)
(check-type n (integer 1))
(let ((size (1+ (* 2 n))))
(make-array (list size size) :element-type 'bit
:initial-element 0)))
(defun copy-tableau (tab)
"Creates a copy of TAB and returns it."
(let ((copy (make-tableau-zero-state (tableau-qubits tab))))
(loop :for i :below (array-total-size copy)
:do (setf (row-major-aref copy i)
(row-major-aref tab i)))
copy))
(declaim (inline tableau-qubits
tableau-x (setf tableau-x)
tableau-z (setf tableau-z)
tableau-r (setf tableau-r)
tableau-scratch (setf tableau-scratch)))
(defun tableau-qubits (tab)
"How many qubits does the tableau TAB represent?"
(declare (type tableau tab))
(the tableau-index (ash (1- (array-dimension tab 0)) -1)))
(defun tableau-x (tab i j)
(declare (type tableau tab)
(type tableau-index i j))
(aref tab i j))
(defun (setf tableau-x) (new-bit tab i j)
(declare (type tableau tab)
(type tableau-index i j)
(type bit new-bit))
(setf (aref tab i j) new-bit))
(defun tableau-z (tab i j)
(declare (type tableau tab)
(type tableau-index i j))
(aref tab i (+ j (tableau-qubits tab))))
(defun (setf tableau-z) (new-bit tab i j)
(declare (type tableau tab)
(type tableau-index i j)
(type bit new-bit))
(setf (aref tab i (+ j (tableau-qubits tab))) new-bit))
(defun tableau-r (tab i)
(declare (type tableau tab)
(type tableau-index i))
(aref tab i (* 2 (tableau-qubits tab))))
(defun (setf tableau-r) (new-bit tab i)
(declare (type tableau tab)
(type tableau-index i)
(type bit new-bit))
(setf (aref tab i (* 2 (tableau-qubits tab))) new-bit))
(defun tableau-scratch (tab i)
(declare (type tableau tab)
(type tableau-index i))
(aref tab (* 2 (tableau-qubits tab)) i))
(defun (setf tableau-scratch) (new-bit tab i)
(declare (type tableau tab)
(type tableau-index i)
(type bit new-bit))
(setf (aref tab (* 2 (tableau-qubits tab)) i) new-bit))
(defun tableau-clear-scratch (tab)
"Clear the scratch row of TAB."
(dotimes (i (1+ (* 2 (tableau-qubits tab))))
(setf (tableau-scratch tab i) 0)))
(defun display-row (tab i)
(cond
((= 1 (tableau-r tab i))
(write-string "-"))
(t
(write-string "+")))
(loop :for j :below (tableau-qubits tab) :do
(let ((x (tableau-x tab i j))
(z (tableau-z tab i j)))
(cond
((and (= 0 x) (= 0 z)) (write-string "I"))
((and (= 1 x) (= 0 z)) (write-string "X"))
((and (= 0 x) (= 1 z)) (write-string "Z"))
((and (= 1 x) (= 1 z)) (write-string "Y"))))))
(defun tableau-copy-row (tab i k)
"Given a tableau TAB, overwrite row I with row K."
(declare (type tableau tab)
(type tableau-index i k))
(dotimes (j (array-dimension tab 1))
(setf (aref tab i j) (aref tab k j))))
(defun tableau-swap-row (tab i k)
"Given a tableau TAB, swap row I with row K."
(declare (type tableau tab)
(type tableau-index i k))
(dotimes (j (1+ (* 2 (tableau-qubits tab))))
(rotatef (aref tab i j) (aref tab k j))))
(defun display-tableau (tab)
"Display the tableau TAB a la Aaronson's CHP program."
(let ((n (tableau-qubits tab)))
(loop :for i :below (* 2 n) :do
(display-row tab i)
(terpri)
(when (= n (1+ i))
(loop :repeat (1+ n) :do
(write-char #\-))
(terpri)))))
(defun zero-out-tableau (tab)
"Bring the tableau to the zero state."
(dotimes (i (array-total-size tab))
(setf (row-major-aref tab i) 0))
(dotimes (i (* 2 (tableau-qubits tab)))
(setf (aref tab i i) 1)))
(defun make-tableau-zero-state (n)
"Create a tableau of N qubits in the zero state."
(let ((zero (make-blank-tableau n)))
(dotimes (i (* 2 n) zero)
(setf (aref zero i i) 1))))
(defun take-tableau-to-basis-state (tab x)
"Bring the tableau to the specific basis state X. X is an integer interpreted as a collection of bits, so for example, |01000> = #b01000 = 8."
(assert (>= (tableau-qubits tab) (integer-length x)))
(let ((n (tableau-qubits tab)))
(zero-out-tableau tab)
(dotimes (i n)
(when (logbitp i x)
(setf (tableau-r tab (+ i n)) 1)))))
(declaim (inline phase-of-product))
(defun phase-of-product (x1 z1 x2 z2)
This function is called " g " in the et al . paper .
(declare (type bit x1 z1 x2 z2))
(levi-civita (logior x1 (ash z1 1))
(logior x2 (ash z2 1))))
(declaim (inline %band b* %bior bmax %bxor b+ bnot))
(defun %band (a b)
(declare (type bit a b))
(the bit (logand a b)))
(defun b* (&rest bits)
(declare (dynamic-extent bits))
(let ((result 1))
(declare (type bit result))
(dolist (bit bits result)
(setf result (%band result bit)))))
(defun %bior (a b)
(declare (type bit a b))
(the bit (logior a b)))
(defun bmax (&rest bits)
(declare (dynamic-extent bits))
(let ((result 0))
(declare (type bit result))
(dolist (bit bits result)
(setf result (%bior result bit)))))
(defun %bxor (a b)
(declare (type bit a b))
(the bit (logxor a b)))
(defun b+ (&rest bits)
(declare (dynamic-extent bits))
(let ((result 0))
(declare (type bit result))
(dolist (bit bits result)
(setf result (%bxor result bit)))))
(defun bnot (b)
(declare (type bit b))
(the bit (- 1 b)))
(define-modify-macro xorf (x) %bxor)
(defun incurred-phase-from-row-product (tab h i)
"Calculate the incurred phase by multiplying row H and row I together."
(mod (+ (* 2 (tableau-r tab h))
(* 2 (tableau-r tab i))
(loop :with sum :of-type fixnum := 0
:for j :below (tableau-qubits tab)
:for ph := (phase-of-product
(tableau-x tab i j)
(tableau-z tab i j)
(tableau-x tab h j)
(tableau-z tab h j))
:do (incf sum ph)
:finally (return sum)))
4))
(declaim (inline row-product))
(defun row-product (tab h i &key allow-dirty-phase)
"Set generator h to h + i, where + is the Pauli group operation. When ALLOW-DIRTY-PHASE is true, phases are allowed to be i or -i."
will eventually have a phase of 1 or -1 , the phase may take the
(let ((sum (incurred-phase-from-row-product tab h i)))
Step 1
(cond
((= 0 sum) (setf (tableau-r tab h) 0))
((= 2 sum) (setf (tableau-r tab h) 1))
((not allow-dirty-phase)
(error "invalid prod between row ~D and ~D (got ~D, which is an invalid phase for a generator or antigenerator!):~%~A~%~A~%" h i sum
(with-output-to-string (*standard-output*)
(display-row tab h))
(with-output-to-string (*standard-output*)
(display-row tab i)))))
Step 2
(dotimes (j (tableau-qubits tab))
(xorf (tableau-x tab h j) (tableau-x tab i j))
(xorf (tableau-z tab h j) (tableau-z tab i j)))
sum))
a phase of 1 or -1 , the phase may take the value of i or -i in
( can be 1 , i , -1 , or -i ) .
(defun multiply-into-scratch (tab i)
"Multiplies row I of TAB into the scratch row, and return the phase produced by the multiplication (as 0, 1, 2, 3 for 1, i, -1, -i respectively)."
(declare (notinline row-product))
(let ((n (tableau-qubits tab)))
(prog1 (row-product tab (* 2 n) i :allow-dirty-phase t)
(setf (tableau-r tab (* 2 n)) 0))))
(defun clifford-stabilizer-action (c)
"Compute a symbolic representation of the action of the Clifford element C on the stabilizer representation of a state, namely the \"tableau representation\".
Given a Clifford C, calculate two values:
1. A list of variable names representing X-Z pairs on qubits 0, 1, .... A typical value will look like
(X0 Z0 X1 Z1 ... Xn Zn),
but the symbols may be uninterned or named differently.
2. A list of updates to the variables of (1), represented as Boolean expressions. Similarly to (2), these are expressions in 1-1 correspondence with (1) which, if evaluated, would produce the updates to said variables.
Note that no expressions calculating the phase update are created. This is because these phase updates are calculated by the function generate-clifford-image-phase instead."
(let* ((num-qubits (clifford-num-qubits c))
(num-variables (* 2 num-qubits))
(variables (loop :for i :below num-variables
:collect (if (evenp i)
(alexandria:format-symbol nil "X~D" (floor i 2))
(alexandria:format-symbol nil "Z~D" (floor i 2)))))
(new-variables (make-array num-variables :initial-element nil)))
We will be mapping over all operating on a single
qubit . We will compute the action on the and use this to
(map-all-paulis num-qubits
(lambda (i p)
(let* ((cp (apply-clifford c p)))
When is a generator ( i.e. , X or
under C. Similarly to the last loop , we
Pauli _ acted on by the _ ( CP
X and Z 's will have power of two indexes .
(let ((var (nth (1- (integer-length i)) variables)))
(loop :with bits := (pauli-index cp)
:for i :below num-variables
:do (push (if (= 1 (ldb (byte 1 0) bits)) var 0) (aref new-variables i)) (setf bits (ash bits -1))))))))
(map-into new-variables (lambda (sum) `(b+ ,@sum)) new-variables)
(values
variables
(coerce new-variables 'list))))
Many moons ago ( 04/2019 ) , the phase updates produced by a acting on
were updated based on values in the un - clifforded tableau , but in
It does this ( with a minor adjustment or two ) by :
2 ) Mapping each of these paulis to their image under ,
image of the entire tableau row under the .
1 for each Y. This is because in the original row , the -i factor
that comes from XZ = -iY is adjusted to 0 , so we need to do the
(defun generate-clifford-image-phase (tab-var c row-var qubit-vars)
"Calculate the phase update to a specific row in the tableau TAB, when acted on by a clifford C on specific qubits."
(let* ((cn (num-qubits c))
(images (clifford-basis-map c)))
(alexandria:with-gensyms (row-image y-phase-offset Xq Zq Yq)
`(let ((,row-image (make-components ,cn))
(,y-phase-offset 0))
(declare (type fixnum ,y-phase-offset)
(type pauli-components ,row-image))
,@(loop :for i :below (length qubit-vars)
:for q :in (reverse qubit-vars)
:collect `(let* ((,Xq (tableau-x ,tab-var ,row-var ,q))
(,Zq (tableau-z ,tab-var ,row-var ,q))
(,Yq (logand ,Xq ,Zq)))
(declare (type bit ,Xq ,Yq ,Zq))
(when (= 1 ,Xq) (multiply-components-into ,row-image ,(pauli-components (aref images (* 2 i))) ,row-image))
(when (= 1 ,Zq) (multiply-components-into ,row-image ,(pauli-components (aref images (1+ (* 2 i)))) ,row-image))
(incf ,y-phase-offset ,Yq)))
(floor (mod (the fixnum (+ ,y-phase-offset (aref ,row-image 0))) 4) 2)))))
(defun compile-tableau-operation (c)
"Compile a Clifford element into a tableau operation. This will be a lambda form whose first argument is the tableau to operate on, and whose remaining arguments are the qubit indexes to operate on. Upon applying this function to a tableau, it will be mutated "
(check-type c clifford)
(let* ((num-qubits (num-qubits c))
(i (gensym "I-"))
(tab (gensym "TAB-"))
(qubits (loop :for i :below num-qubits
:collect (alexandria:format-symbol nil "Q~D" (- num-qubits 1 i)))))
(multiple-value-bind (variables new-variables)
(clifford-stabilizer-action c)
return values of CLIFFORD - STABILIZER - ACTION . See the
`(lambda (,tab ,@qubits)
(declare (optimize speed (safety 0) (debug 0) (space 0) (compilation-speed 0))
(type tableau ,tab)
(type tableau-index ,@qubits))
(dotimes (,i (* 2 (tableau-qubits ,tab)))
(declare (type tableau-index ,i))
First , we construct bindings to these variables
(let (,@(loop :for qubit :in (reverse qubits)
:for (x z) :on variables :by #'cddr
:collect `(,x (tableau-x ,tab ,i ,qubit))
:collect `(,z (tableau-z ,tab ,i ,qubit))))
(declare (type bit ,@variables))
(xorf (tableau-r ,tab ,i) ,(generate-clifford-image-phase tab c i qubits))
(setf
,@(loop :for qubit :in (reverse qubits)
:for (x z) :on new-variables :by #'cddr
:collect `(tableau-x ,tab ,i ,qubit)
:collect x
:collect `(tableau-z ,tab ,i ,qubit)
:collect z))))))))
(defun tableau-function (c)
"Given a Clifford C, return a function representing its action on a tableau."
(compile nil (compile-tableau-operation c)))
These functions : TABLEAU - APPLY-{CNOT , H , PHASE } are hard - coded
from the et al . paper . These can be readily generated
(defun tableau-apply-cnot (tab a b)
(declare (type tableau tab)
(type tableau-index a b))
(dotimes (i (* 2 (tableau-qubits tab)))
(xorf (tableau-r tab i) (logand (tableau-x tab i a)
(tableau-z tab i b)
(logxor 1
(tableau-x tab i b)
(tableau-z tab i a))))
(xorf (tableau-x tab i b) (tableau-x tab i a))
(xorf (tableau-z tab i a) (tableau-z tab i b))))
(defun tableau-apply-h (tab q)
(declare (type tableau tab)
(type tableau-index q))
(dotimes (i (* 2 (tableau-qubits tab)))
(xorf (tableau-r tab i) (logand (tableau-x tab i q) (tableau-z tab i q)))
(rotatef (tableau-x tab i q) (tableau-z tab i q))))
(defun tableau-apply-phase (tab q)
(declare (type tableau tab)
(type tableau-index q))
(dotimes (i (* 2 (tableau-qubits tab)))
(xorf (tableau-r tab i) (logand (tableau-x tab i q) (tableau-z tab i q)))
(xorf (tableau-z tab i q) (tableau-x tab i q))))
(declaim (inline tableau-set-row-to-pauli tableau-copy-row))
(defun tableau-set-row-to-pauli (tab i b)
"Given a tableau TAB, set row I to be the single qubit Pauli term B, where if 0 <= B < N, the X_B will be set, and if N <= B < 2*N, then Z_(B - N) will be set."
(declare (type tableau tab)
(type tableau-index i b))
(dotimes (j (array-dimension tab 1))
(setf (aref tab i j) 0))
(setf (aref tab i b) 1)
nil)
: For some reason that I 'm not sure about , the procedure for
non - deterministic measurement from the et al . paper
The general idea is a two step operation : ( 1 ) determine if the
measurement would produce a deterministic result , ( 2 ) determine
(defun tableau-measure (tab q)
(declare (optimize speed (safety 0) (debug 0) (space 0) (compilation-speed 0))
(type tableau tab)
(type tableau-index q))
(let* ((n (tableau-qubits tab))
(p (loop :for p :below n
:when (= 1 (tableau-x tab (+ p n) q))
:do (return p)
:finally (return nil))))
(declare (type (or tableau-index null) p)
(type tableau-index n))
(cond
(p
(tableau-copy-row tab p (+ p n))
(tableau-set-row-to-pauli tab (+ p n) (+ q n))
(setf (tableau-r tab (+ p n)) (random 2))
(dotimes (i (* 2 n))
(when (and (/= i p)
(= 1 (tableau-x tab i q)))
(row-product tab i p)))
(values (tableau-r tab (+ p n)) nil))
(t
Zero out the scratch space .
(tableau-clear-scratch tab)
(let ((m (loop :for m :below n
:when (= 1 (tableau-x tab m q))
:do (return m)
:finally (return n))))
(tableau-copy-row tab (* 2 n) (+ m n))
(loop :for i :from (1+ m) :below n :do
(when (= 1 (tableau-x tab i q))
(row-product tab (* 2 n) (+ i n))))
(values (tableau-r tab (* 2 n)) t))))))
(defun put-tableau-into-row-echelon-form (tab)
"Perform Gaussian elimination to put the tableau in row echelon form. Specifically, the modified generators will be put in the form
|1 * * * * * * * * * * *|
|. 1 * * * * * * * * * *|
|. . . 1 * * * * * * * *|
|. . . . . 1 * * * * * *|
|. . 0 . . . . 1 * * * *|
|. . . . . . . . 1 * * *|
^-----X----^ ^----Z-----^
The upper generators comprise only X's and Y's while the lower generators comprise only Z's. This makes it easy to
1) Determine how many nonzero basis states are present, based on the number of purely X/Y generators (which = log(# of nonzero basis states))
2) Easily find a nonzero basis state using the purely Z generators (done in the find-nonzero-operator function below).
Returns the number of purely X/Y generators.
"
(let* ((n (tableau-qubits tab))
(curr-row n))
(flet ((elim-generator (gen-type)
(dotimes (column n)
(let ((gen-row (loop :for gen-row :from curr-row :below (* 2 n)
:when (= 1 (funcall gen-type tab gen-row column))
:do (return gen-row)
:finally (return nil))))
(unless (null gen-row)
(tableau-swap-row tab curr-row gen-row)
(tableau-swap-row tab (- curr-row n) (- gen-row n))
(loop :for elim-row :from (1+ curr-row) :below (* 2 n)
:when (= 1 (funcall gen-type tab elim-row column))
:do (row-product tab elim-row curr-row)
(row-product tab (- curr-row n) (- elim-row n)))
(incf curr-row))))))
Eliminate X 's to get upper generators ( X / Y only )
(elim-generator #'tableau-x)
(prog1 (- curr-row n)
Eliminate Z 's to get lower generators ( Z only )
(elim-generator #'tableau-z)))))
(defun find-nonzero-operator (tab)
"Given a tableau TAB, find a Pauli operator P such that P|0...0> has nonzero amplitude in the state represented by TAB. Write this operator to the scratch space of TAB. This function also puts TAB into REF (row echelon form), since P is found using the purely Z generators."
(let ((n (tableau-qubits tab))
(log-nonzero (put-tableau-into-row-echelon-form tab)))
Zero out scratch space
(tableau-clear-scratch tab)
(loop :for row :from (1- (* 2 n)) :downto (+ n log-nonzero)
:do (let ((phase (tableau-r tab row))
(first-z n))
(loop :for j :from (1- n) :downto 0
:when (= 1 (tableau-z tab row j))
:do (setf first-z j)
(when (= 1 (tableau-scratch tab j))
(xorf phase 1)))
Change the corresponding X in the P operator as necessary
(when (= phase 1)
(xorf (tableau-scratch tab first-z) 1))))))
(defun read-basis-state-from-scratch-row (tab)
"Given a tableau TAB, read off the operator on the scratch row as a basis state. Returns two values:
1) the basis state as an integer
2) the phase of the state as an integer."
(let* ((n (tableau-qubits tab))
(state 0)
(phase 0))
(dotimes (i n)
(when (= 1 (tableau-x tab (* 2 n) i))
(incf state (expt 2 i))
(when (= 1 (tableau-z tab (* 2 n) i))
(incf phase))))
(values state phase)))
The two nested dotimes in this function are a little mysterious ,
(defun tableau-wavefunction (tab)
"Given a tableau TAB, generate and return the wavefunction representation of the stabilizer state the tableau represents, using the normalized sum of all stabilizers.
Note: the scratch space is used as an area to write intermediate state values, and starts with the operator returned by find-nonzero-operator."
(let* ((n (tableau-qubits tab))
(log-nonzero (put-tableau-into-row-echelon-form tab))
(norm (sqrt (expt 2 log-nonzero)))
(wf (make-array (expt 2 n) :element-type '(complex double-float) :initial-element #C(0.0d0 0.0d0)))
(running-phase 0))
(find-nonzero-operator tab)
(dotimes (i (expt 2 log-nonzero))
(let ((x (logxor i (1+ i))))
(dotimes (j log-nonzero)
(when (logbitp j x)
(incf running-phase (multiply-into-scratch tab (+ n j)))))
(multiple-value-bind (state read-phase) (read-basis-state-from-scratch-row tab)
(setf (aref wf state) (/ (expt #C(0.0d0 1.0d0) (+ read-phase running-phase)) norm)))))
wf))
The .chp file format is an input to 's chp program written
in is a parser and interpreter for it .
(defun interpret-chp (code tab &key silent)
(let ((*standard-output* (if silent (make-broadcast-stream) *standard-output*)))
(loop :for i :from 1
:for isn :in code
:do
(format t "~D: ~A" i isn)
(alexandria:destructuring-ecase isn
((H q) (tableau-apply-h tab q))
((S q) (tableau-apply-phase tab q))
((CNOT p q) (tableau-apply-cnot tab p q))
((MEASURE q) (multiple-value-bind (outcome determ?)
(tableau-measure tab q)
(format t " => ~D~:[ (random)~;~]" outcome determ?))))
(terpri))))
(defun read-chp-file (file)
"Parse a .chp file as defined by Aaronson."
(let ((max-qubit 0))
(labels ((parse-gate (gate-name)
(cond
((string= gate-name "h") 'H)
((string= gate-name "c") 'CNOT)
((string= gate-name "p") 'S)
((string= gate-name "m") 'MEASURE)
(t (error "Invalid gate name: ~S" gate-name))))
(parse-qubits (qubits)
(loop :with seen := 0
:for qubit-string :in qubits
:for qubit := (parse-integer qubit-string :junk-allowed nil)
:collect (progn
(when (minusp qubit)
(error "Qubits must be non-negative integers"))
(when (logbitp qubit seen)
(error "Can't have duplicate qubits: ~A" qubits))
(setf seen (dpb 1 (byte 1 qubit) seen))
(setf max-qubit (max max-qubit qubit))
qubit)))
(parse-line (line)
(let ((split (split-sequence:split-sequence #\Space line :remove-empty-subseqs t)))
(cond
((null split)
nil)
(t
(destructuring-bind (gate . qubits) split
(when (null qubits)
(error "Invalid line, need qubits: ~S" line))
(cons (parse-gate gate) (parse-qubits qubits))))))))
(with-open-file (s file :direction ':input)
(loop :for line := (read-line s nil ':eof)
:do (cond
((eq ':eof line) (error "Didn't find a # line"))
((string= line "#") (loop-finish))))
(values (loop :for line := (read-line s nil ':eof)
:until (eq ':eof line)
:for parsed-line := (parse-line line)
:when parsed-line
:collect parsed-line)
(1+ max-qubit))))))
(defun interpret-chp-file (file)
"Execute one of Aaronson's .chp files."
(multiple-value-bind (code num-qubits)
(read-chp-file file)
(let ((tab (make-tableau-zero-state num-qubits)))
(interpret-chp code tab))))
(defun random-chp-and-quil (q n)
"Generates a random CHP circuit on q qubits, of n gates.
Outputs two values:
1) The parsed CHP format of the random circuit
2) The equivalent random circuit in quil.
Intended for testing purposes."
(let ((quil-str (make-string-output-stream)))
(values
(loop :repeat n
:for q1 := (random q)
:for q2 := (mod (+ q1 (1+ (random (1- q)))) q)
:for chp-gate := (alexandria:whichever
`(H ,q1)
`(S ,q1)
`(CNOT ,q1 ,q2))
:for quil-gate := (format nil "~{~A~^ ~}" chp-gate)
:collect chp-gate
:do (write-line quil-gate quil-str))
(get-output-stream-string quil-str))))
|
eb4437556bf5f7bf9565311699e3269a5a14b511f225bc9502fdb38fbc0916d5 | ocaml-sf/learn-ocaml-corpus | test.ml | open Printf
let iter = List.iter
let map = List.map
module T = Test_lib
module R = Report
type report = R.t
(* Determinism. *)
let () = Random.init 0
(* The auto-grader. *)
(* -------------------------------------------------------------------------- *)
(* Some of the code below should move to separate library files. *)
(* -------------------------------------------------------------------------- *)
(* Miscellaneous. *)
let postincrement c =
let n = !c in
c := n + 1;
n
(* -------------------------------------------------------------------------- *)
(* PPrintMini. *)
(* -------------------------------------------------------------------------- *)
(* A type of integers with infinity. *)
type requirement =
int (* with infinity *)
Infinity is encoded as [ max_int ] .
let infinity : requirement =
max_int
(* Addition of integers with infinity. *)
let (++) (x : requirement) (y : requirement) : requirement =
if x = infinity || y = infinity then
infinity
else
x + y
Comparison between an integer with infinity and a normal integer .
let (<==) (x : requirement) (y : int) =
x <= y
(* -------------------------------------------------------------------------- *)
The type of documents . See [ ] for documentation .
type document =
| Empty
| FancyString of string * int * int * int
| Blank of int
| IfFlat of document * document
| HardLine
| Cat of requirement * document * document
| Nest of requirement * int * document
| Group of requirement * document
(* -------------------------------------------------------------------------- *)
(* Retrieving or computing the space requirement of a document. *)
let rec requirement = function
| Empty ->
0
| FancyString (_, _, _, len)
| Blank len ->
len
| IfFlat (doc1, _) ->
requirement doc1
| HardLine ->
infinity
| Cat (req, _, _)
| Nest (req, _, _)
| Group (req, _) ->
req
(* -------------------------------------------------------------------------- *)
(* Document constructors. *)
let empty =
Empty
let fancysubstring s ofs len apparent_length =
if len = 0 then
empty
else
FancyString (s, ofs, len, apparent_length)
let fancystring s apparent_length =
fancysubstring s 0 (String.length s) apparent_length
let utf8_length s =
let rec length_aux s c i =
if i >= String.length s then c else
let n = Char.code (String.unsafe_get s i) in
let k =
if n < 0x80 then 1 else
if n < 0xe0 then 2 else
if n < 0xf0 then 3 else 4
in
length_aux s (c + 1) (i + k)
in
length_aux s 0 0
let utf8string s =
fancystring s (utf8_length s)
let utf8format f =
ksprintf utf8string f
let char c =
assert (c <> '\n');
fancystring (String.make 1 c) 1
let space =
char ' '
let semicolon =
char ';'
let hardline =
HardLine
let blank n =
match n with
| 0 ->
empty
| 1 ->
space
| _ ->
Blank n
let ifflat doc1 doc2 =
match doc1 with
| IfFlat (doc1, _)
| doc1 ->
IfFlat (doc1, doc2)
let internal_break i =
ifflat (blank i) hardline
let break0 =
internal_break 0
let break1 =
internal_break 1
let break i =
match i with
| 0 ->
break0
| 1 ->
break1
| _ ->
internal_break i
let (^^) x y =
match x, y with
| Empty, _ ->
y
| _, Empty ->
x
| _, _ ->
Cat (requirement x ++ requirement y, x, y)
let nest i x =
assert (i >= 0);
Nest (requirement x, i, x)
let group x =
let req = requirement x in
if req = infinity then
x
else
Group (req, x)
(* -------------------------------------------------------------------------- *)
(* Printing blank space (indentation characters). *)
let blank_length =
80
let blank_buffer =
String.make blank_length ' '
let rec blanks output n =
if n <= 0 then
()
else if n <= blank_length then
Buffer.add_substring output blank_buffer 0 n
else begin
Buffer.add_substring output blank_buffer 0 blank_length;
blanks output (n - blank_length)
end
(* -------------------------------------------------------------------------- *)
(* The rendering engine maintains the following internal state. *)
(* For simplicity, the ribbon width is considered equal to the line
width; in other words, there is no ribbon width constraint. *)
(* For simplicity, the output channel is required to be an OCaml buffer.
It is stored within the [state] record. *)
type state =
{
(* The line width. *)
width: int;
(* The current column. *)
mutable column: int;
(* The output buffer. *)
mutable output: Buffer.t;
}
(* -------------------------------------------------------------------------- *)
(* For simplicity, the rendering engine is *not* in tail-recursive style. *)
let rec pretty state (indent : int) (flatten : bool) doc =
match doc with
| Empty ->
()
| FancyString (s, ofs, len, apparent_length) ->
Buffer.add_substring state.output s ofs len;
state.column <- state.column + apparent_length
| Blank n ->
blanks state.output n;
state.column <- state.column + n
| HardLine ->
assert (not flatten);
Buffer.add_char state.output '\n';
blanks state.output indent;
state.column <- indent
| IfFlat (doc1, doc2) ->
pretty state indent flatten (if flatten then doc1 else doc2)
| Cat (_, doc1, doc2) ->
pretty state indent flatten doc1;
pretty state indent flatten doc2
| Nest (_, j, doc) ->
pretty state (indent + j) flatten doc
| Group (req, doc) ->
let flatten = flatten || state.column ++ req <== state.width in
pretty state indent flatten doc
(* -------------------------------------------------------------------------- *)
(* The engine's entry point. *)
let pretty width doc =
let output = Buffer.create 512 in
let state = { width; column = 0; output } in
pretty state 0 false doc;
Buffer.contents output
(* -------------------------------------------------------------------------- *)
(* Additions to PPrintMini. *)
let separate (sep : 'a) (xs : 'a list) : 'a list =
match xs with
| [] ->
[]
| x :: xs ->
x :: List.flatten (List.map (fun x -> [sep; x]) xs)
let concat (docs : document list) : document =
List.fold_right (^^) docs empty
let comma =
utf8string "," ^^ break 1
let commas docs =
concat (separate comma docs)
let semi =
utf8string ";" ^^ break 1
let semis docs =
concat (separate semi docs)
let int i =
utf8format "%d" i
let block b doc =
nest 2 (break b ^^ doc) ^^ break b
let parens doc =
utf8string "(" ^^ block 0 doc ^^ utf8string ")"
let brackets doc =
utf8string "[" ^^ block 0 doc ^^ utf8string "]"
let ocaml_array_brackets doc =
utf8string "[| " ^^ block 0 doc ^^ utf8string "|]"
let tuple docs =
group (parens (commas docs))
let list docs =
group (brackets (semis docs))
let construct label docs =
match docs with
| [] ->
utf8string label
| _ ->
utf8string label ^^ space ^^ tuple docs
let flow docs =
match docs with
| [] ->
[]
| doc :: docs ->
doc :: map (fun doc -> group (break 1) ^^ doc) docs
let raw_apply docs =
group (concat (flow docs))
let apply f docs =
raw_apply (utf8string f :: docs)
let parens_apply f docs =
parens (apply f docs)
let piped_apply f docs =
(* Isolate the last argument. *)
assert (List.length docs > 0);
let docs = List.rev docs in
let doc, docs = List.hd docs, List.rev (List.tl docs) in
(* Print. *)
group (doc ^^ break 1 ^^ utf8string "|>" ^^ space ^^ apply f docs)
let infix_apply op doc1 doc2 =
group (
group (doc1 ^^ break 1 ^^ utf8string op) ^^ break 1 ^^
doc2
)
let elet x doc1 doc2 =
group (
group (
utf8format "let %s =" x ^^
block 1 doc1 ^^
utf8string "in"
) ^^ break 1 ^^
doc2
)
let wrap (print : 'a -> document) : 'a -> string =
fun x -> pretty 70 (group (print x))
(* -------------------------------------------------------------------------- *)
(* An implementation of symbolic sequences. *)
module SymSeq = struct
type _ seq =
| Empty : 'a seq
| Singleton: 'a -> 'a seq
| Sum : int * 'a seq * 'a seq -> 'a seq
| Product : int * 'a seq * 'b seq -> ('a * 'b) seq
| Map : int * ('a -> 'b) * 'a seq -> 'b seq
exception OutOfBounds
let length (type a) (s : a seq) : int =
match s with
| Empty ->
0
| Singleton _ ->
1
| Sum (length, _, _) ->
length
| Product (length, _, _) ->
length
| Map (length, _, _) ->
length
let is_empty s =
length s = 0
let empty =
Empty
let singleton x =
Singleton x
let check length =
assert (length >= 0); (* if this fails, an overflow has occurred *)
length
let sum s1 s2 =
if is_empty s1 then s2
else if is_empty s2 then s1
else Sum (check (length s1 + length s2), s1, s2)
let bigsum ss =
List.fold_left sum empty ss
let product s1 s2 =
if is_empty s1 || is_empty s2 then
empty
else
Product (check (length s1 * length s2), s1, s2)
let map phi s =
if is_empty s then
empty
else
Map (length s, phi, s)
let rec get : type a . a seq -> int -> a =
fun s i ->
match s with
| Empty ->
raise OutOfBounds
| Singleton x ->
if i = 0 then x else raise OutOfBounds
| Sum (_, s1, s2) ->
let n1 = length s1 in
if i < n1 then get s1 i
else get s2 (i - n1)
| Product (_, s1, s2) ->
let q, r = i / length s2, i mod length s2 in
get s1 q, get s2 r
| Map (_, phi, s) ->
phi (get s i)
let rec foreach : type a . a seq -> (a -> unit) -> unit =
fun s k ->
match s with
| Empty ->
()
| Singleton x ->
k x
| Sum (_, s1, s2) ->
foreach s1 k;
foreach s2 k
| Product (_, s1, s2) ->
foreach s1 (fun x1 ->
foreach s2 (fun x2 ->
k (x1, x2)
)
)
| Map (_, phi, s) ->
foreach s (fun x -> k (phi x))
let elements (s : 'a seq) : 'a list =
let xs = ref [] in
foreach s (fun x -> xs := x :: !xs);
List.rev !xs
For some reason , [ Random.int ] stops working at [ 2 ^ 30 ] .
let rec random_int n =
let threshold = 1 lsl 30 in
if n < threshold then
Random.int n
else
failwith "Can't sample over more than 2^30 elements."
(* Extract a list of at most [threshold] elements from the sequence [s]. *)
let sample threshold (s : 'a seq) : 'a list =
if length s <= threshold then
(* If the sequence is short enough, keep of all its elements. *)
elements s
else
(* Otherwise, keep a randomly chosen sample. *)
let xs = ref [] in
for i = 1 to threshold do
let i = random_int (length s) in
let x = get s i in
xs := x :: !xs
done;
!xs
end
type 'a seq =
'a SymSeq.seq
(* -------------------------------------------------------------------------- *)
(* A fixed point combinator. *)
let fix : type a b . ((a -> b) -> (a -> b)) -> (a -> b) =
fun ff ->
let table = Hashtbl.create 128 in
let rec f (x : a) : b =
try
Hashtbl.find table x
with Not_found ->
let y = ff f x in
Hashtbl.add table x y;
y
in
f
let curry f x y = f (x, y)
let uncurry f (x, y) = f x y
let fix2 : type a b c . ((a -> b -> c) -> (a -> b -> c)) -> (a -> b -> c) =
fun ff ->
let ff f = uncurry (ff (curry f)) in
curry (fix ff)
(* -------------------------------------------------------------------------- *)
(* MiniFeat. *)
module Feat = struct
Core combinators .
type 'a enum =
int -> 'a SymSeq.seq
let empty : 'a enum =
fun _s ->
SymSeq.empty
let zero =
empty
let enum (xs : 'a SymSeq.seq) : 'a enum =
fun s ->
if s = 0 then xs else SymSeq.empty
let just (x : 'a) : 'a enum =
(* enum (SymSeq.singleton x) *)
fun s ->
if s = 0 then SymSeq.singleton x else SymSeq.empty
let pay (enum : 'a enum) : 'a enum =
fun s ->
if s = 0 then SymSeq.empty else enum (s-1)
let sum (enum1 : 'a enum) (enum2 : 'a enum) : 'a enum =
fun s ->
SymSeq.sum (enum1 s) (enum2 s)
let ( ++ ) =
sum
let rec _up i j =
if i <= j then
i :: _up (i + 1) j
else
[]
let product (enum1 : 'a enum) (enum2 : 'b enum) : ('a * 'b) enum =
fun s ->
SymSeq.bigsum (
List.map (fun s1 ->
let s2 = s - s1 in
SymSeq.product (enum1 s1) (enum2 s2)
) (_up 0 s)
)
let ( ** ) =
product
let balanced_product (enum1 : 'a enum) (enum2 : 'b enum) : ('a * 'b) enum =
fun s ->
if s mod 2 = 0 then
let s = s / 2 in
SymSeq.product (enum1 s) (enum2 s)
else
let s = s / 2 in
SymSeq.sum
(SymSeq.product (enum1 s) (enum2 (s+1)))
(SymSeq.product (enum1 (s+1)) (enum2 s))
let ( *-* ) =
balanced_product
let map (phi : 'a -> 'b) (enum : 'a enum) : 'b enum =
fun s ->
SymSeq.map phi (enum s)
(* Convenience functions. *)
let finite (xs : 'a list) : 'a enum =
List.fold_left (++) zero (List.map just xs)
let bool : bool enum =
just false ++ just true
let list (elem : 'a enum) : 'a list enum =
let cons (x, xs) = x :: xs in
fix (fun list ->
just [] ++ pay (map cons (elem ** list))
)
let nonempty_list (elem : 'a enum) : 'a list enum =
let cons (x, xs) = x :: xs in
map cons (elem ** list elem)
(* Extract a list of at most [threshold] elements of each size,
for every size up to [s] (included), from the enumeration [e]. *)
let sample threshold s (e : 'a enum) : 'a list =
List.flatten (
List.map (fun i ->
SymSeq.sample threshold (e i)
) (_up 0 s)
)
end
type 'a enum =
'a Feat.enum
(* -------------------------------------------------------------------------- *)
Generic testing utilities .
(* When we fail, the exception carries a learn-ocaml report. *)
exception Fail of report
(* [section title report] encloses the report [report] within a section
entitled [title], producing a larger report. *)
let section title report : report =
[R.Section ([R.Text title], report)]
(* This generic function takes as an argument the text of the message that
will be displayed. A message is a list of inline things. *)
let fail (text : R.inline list) =
let report = [R.Message (text, R.Failure)] in
raise (Fail report)
(* This is a special case where the message is a singleton list containing
a single string. The string can be formatted using a printf format. *)
let fail_text format =
Printf.ksprintf (fun s -> fail [R.Text s]) format
(* [protect f] evaluates [f()], which either returns normally and produces a
report, or raises [Fail] and produces a report. In either case, the report
is returned. *)
(* If an unexpected exception is raised, in student code or in grading code,
the exception is displayed as part of a failure report. (Ideally, grading
code should never raise an exception!) It is debatable whether one should
show just the name of the exception, or a full backtrace; I choose the
latter, on the basis that more information is always preferable. *)
let protect f =
try
T.run_timeout f
with
| Fail report ->
report
| TODO ->
let text = [
R.Text "Not yet implemented."
] in
let report = [R.Message (text, R.Failure)] in
report
| (e : exn) ->
let text = [
R.Text "The following exception is raised and never caught:";
R.Break;
R.Output (Printexc.to_string e);
R.Output (Printexc.get_backtrace());
] in
let report = [R.Message (text, R.Failure)] in
report
(* [successful] tests whether a report is successful. *)
let successful_status = function
| R.Success _
| R.Warning
| R.Informative
| R.Important ->
true
| R.Failure ->
false
let rec successful_item = function
| R.Section (_, r) ->
successful r
| R.Message (_, status) ->
successful_status status
and successful (r : report) =
List.for_all successful_item r
let (-@>) (r : report) (f : unit -> report) : report =
if successful r then
r @ f()
else
r
(* -------------------------------------------------------------------------- *)
Generic test functions .
let grab ty name k =
T.test_value (T.lookup_student ty name) k
let test_value_0 name ty reference eq =
grab ty name (fun candidate ->
protect (fun () ->
if not (eq candidate reference) then
fail [
R.Code name; R.Text "is incorrect.";
];
let message = [ R.Code name; R.Text "is correct."; ] in
[ R.Message (message, R.Success 1) ]
)
)
let correct name =
let message = [ R.Code name; R.Text "seems correct."; ] in
[ R.Message (message, R.Success 1) ]
let correct2 name1 name2 =
let message = [ R.Code name1; R.Text "and"; R.Code name2; R.Text "seem correct."; ] in
[ R.Message (message, R.Success 1) ]
(* When doing black-box testing of a complete module, we are not testing just
one function in isolation, but a group of functions together. In that case,
the wording of the error message is somewhat different. Instead of saying
that a specific function is incorrect, we want to say that an expression
[expr] yields an incorrect result. *)
let eq_behavior eq_value actual_behavior expected_behavior =
match actual_behavior, expected_behavior with
| Ok actual, Ok expected ->
eq_value actual expected (* value comparison *)
| Error actual, Error expected ->
actual = expected (* exception comparison *)
| Ok _, Error _
| Error _, Ok _ ->
false
let show_actual_behavior show_value behavior =
match behavior with
| Ok v ->
R.Text "produces the following result:" ::
R.Output (show_value v) ::
[]
| Error e ->
R.Text "raises the following exception:" ::
R.Output (Printexc.to_string e) ::
[]
let show_expected_behavior show_value behavior =
match behavior with
| Ok v ->
R.Text "This is invalid. Producing the following result is valid:" ::
R.Output (show_value v) ::
[]
| Error e ->
R.Text "This is invalid. Raising the following exception is valid:" ::
R.Output (Printexc.to_string e) ::
[]
let something_is_wrong =
R.Text "Something is wrong." ::
[]
let incorrect name =
R.Code name :: R.Text "is incorrect." ::
R.Break ::
[]
let black_box_compare
(* Value equality and display, used to compare and show results. *)
eq_value show_value
(* The beginning of the error message. Use [something_is_wrong] or [incorrect name]. *)
announcement
(* Expression display. *)
show_expr expr
(* Actual behavior and expected behavior. *)
actual_behavior
expected_behavior
=
(* Allow [TODO] to escape and abort the whole test. *)
if actual_behavior = Error TODO then
raise TODO
else if not (eq_behavior eq_value actual_behavior expected_behavior) then
fail (
announcement @
R.Text "The following expression:" ::
R.Break ::
R.Code (show_expr expr) ::
R.Break ::
show_actual_behavior show_value actual_behavior @
show_expected_behavior show_value expected_behavior
)
let test_value_1_in_context
(* name and type of the function of interest: *)
name ty
(* reference implementation of this function: *)
reference
(* input transformation function and input printer: *)
make_input print_input
(* output transformation function and output printer: *)
context print_context
(* observation equality test and observation printer: *)
eq show_observation
(* list of inputs: *)
tests
=
(* Beware: [print_input] must produce parentheses if necessary. Also,
[print_context] must enclose its argument in parentheses if necessary. *)
grab ty name (fun candidate ->
protect (fun () ->
tests |> List.iter (fun x ->
let actual_behavior =
T.result (fun () ->
context (candidate (make_input x))
)
and expected_behavior =
T.result (fun () ->
context (reference (make_input x))
)
in
let print () =
print_context (apply name [ print_input x ])
in
black_box_compare
eq show_observation
(incorrect name)
(wrap print) ()
actual_behavior
expected_behavior
);
correct name
)
)
let identity x = x
let test_value_1 name ty reference printx eqy showy tests =
test_value_1_in_context
name ty reference
identity printx
identity identity (* no context *)
eqy showy tests
let test_value_2 name ty reference printx1 printx2 showy eqy tests =
grab ty name (fun candidate ->
protect (fun () ->
tests |> List.iter (fun ((x1, x2) as x) ->
let actual_behavior = T.result (fun () -> candidate x1 x2)
and expected_behavior = T.result (fun () -> reference x1 x2) in
let print_expr () =
apply name [ printx1 x1; printx2 x2 ]
beware : [ printx1 ] and [ ] must produce parentheses
if necessary
if necessary *)
in
black_box_compare
eqy showy
(incorrect name)
(wrap print_expr) ()
actual_behavior
expected_behavior
);
correct name
)
)
let test_value_3 name ty reference printx1 printx2 printx3 showy eqy tests =
grab ty name (fun candidate ->
protect (fun () ->
tests |> List.iter (fun ((x1, x2, x3) as x) ->
let actual_behavior = T.result (fun () -> candidate x1 x2 x3)
and expected_behavior = T.result (fun () -> reference x1 x2 x3) in
let print_expr () =
apply name [ printx1 x1; printx2 x2; printx3 x3 ]
beware : [ printx1 ] , etc . must produce parentheses
if necessary
if necessary *)
in
black_box_compare
eqy showy
(incorrect name)
(wrap print_expr) ()
actual_behavior
expected_behavior
);
correct name
)
)
(* -------------------------------------------------------------------------- *)
(* List-based enumerations. *)
let flat_map f xss =
List.flatten (List.map f xss)
(* [up i j] is the list of the integers of [i] included up to [j] excluded. *)
(* [upk i j k] is [up i j @ k]. *)
let rec upk i j k =
if i < j then
i :: upk (i + 1) j k
else
k
let up i j =
upk i j []
[ pairs xs ys ] is the list of all pairs [ x , y ] where [ x ] is drawn from [ xs ]
and [ y ] is drawn from [ ys ] . In other words , it is the Cartesian product of
the lists [ xs ] and [ ys ] .
and [y] is drawn from [ys]. In other words, it is the Cartesian product of
the lists [xs] and [ys]. *)
let pairs xs ys =
xs |> flat_map (fun x ->
ys |> flat_map (fun y ->
[x, y]
)
)
[ split n f ] enumerates all manners of splitting [ n ] into [ n1 + n2 ] , where
[ n1 ] and [ n2 ] can be zero . For each such split , the enumeration [ f n1 n2 ]
is produced .
[n1] and [n2] can be zero. For each such split, the enumeration [f n1 n2]
is produced. *)
let split n f =
flat_map (fun n1 ->
let n2 = n - n1 in
f n1 n2
) (up 0 (n+1))
(* If [f i] is an enumeration, then [deepening f n] is the concatenation
of the enumerations [f 0, f 1, ... f n]. *)
let deepening (f : int -> 'a list) (n : int) : 'a list =
flat_map f (up 0 (n+1))
(* -------------------------------------------------------------------------- *)
(* Printers. *)
(* A printer for strings. *)
let show_string s =
sprintf "\"%s\"" (String.escaped s)
let print_string s =
utf8string (show_string s)
(* A printer for integers. *)
let print_int =
int
let show_int i =
sprintf "%d" i
(* A printer for characters. *)
let show_char c =
sprintf "'%s'" (Char.escaped c)
let print_char c =
utf8string (show_char c)
A printer for Booleans .
let show_bool b =
if b then "true" else "false"
let print_bool b =
utf8string (show_bool b)
(* A printer for options. *)
let print_option print = function
| None ->
utf8string "None"
| Some x ->
construct "Some" [ print x ]
(* A printer for arrays. *)
let print_array print_element a =
group (ocaml_array_brackets (concat (
a |> Array.map (fun x ->
print_element x ^^ semicolon ^^ break 1
) |> Array.to_list
)))
(* A printer for lists. *)
let print_list print_element xs =
list (map print_element xs)
let print_list_int =
print_list print_int
let show_list_int =
wrap print_list_int
(* -------------------------------------------------------------------------- *)
(* Enumerating all paths into a tree. *)
let rec paths prefix (t : tree) accu =
match t with
| Leaf _ ->
prefix :: accu
| Node (t0, t1) ->
paths (prefix ^ "0") t0 (
paths (prefix ^ "1") t1
accu
)
let paths t =
paths "" t []
(* -------------------------------------------------------------------------- *)
(* A generator for trees. *)
We want to generate trees with distinct leaves . The easiest way of doing so
seems to be to first generate trees with arbitrary data at the leaves , then
( in a separate pass ) populate the leaves with distinct characters .
seems to be to first generate trees with arbitrary data at the leaves, then
(in a separate pass) populate the leaves with distinct characters. *)
module Generate = struct
open Feat
let node (t1, t2) =
Node (t1, t2)
(* A tree of size [n] has [n] nodes, therefore [n+1] leaves. *)
let rec tree : tree enum =
fix (fun tree ->
just (Leaf 'z') ++
pay (map node (tree ** tree))
)
let decorate tree =
let c = ref 0 in
let next () : char =
Char.chr (postincrement c + Char.code 'a')
in
let rec decorate tree =
match tree with
| Leaf _ ->
Leaf (next())
| Node (t0, t1) ->
Node (decorate t0, decorate t1)
in
decorate tree
let all_trees_with_distinct_leaves n =
Generate all trees of size [ n ] , then decorate them . Note that we
do not need to enumerate all permutations of characters at the
leaves ; one permutation suffices to exercise the student 's code .
do not need to enumerate all permutations of characters at the
leaves; one permutation suffices to exercise the student's code. *)
SymSeq.elements (tree n) |> List.map decorate
(* A generator for strings. *)
let character : string enum =
finite [ "a"; "b"; "c"; "d" ]
let glue : string list -> string =
String.concat ""
let string : string enum =
list character |> map glue
(* A generator for strings where each character has a distinct frequency. *)
let successor (c : char) : char =
Char.chr (Char.code c + 1)
let rec distinct_frequency_string (start : char) n =
if n = 0 then
""
else
String.make n start ^
distinct_frequency_string (successor start) (n - 1)
end
(* -------------------------------------------------------------------------- *)
(* A printer for trees. *)
let rec print_tree tree =
match tree with
| Leaf c ->
utf8string "Leaf" ^^ space ^^ print_char c
| Node (t0, t1) ->
construct "Node" [ print_tree t0; print_tree t1 ]
(* Miscellaneous printers. *)
let show_tree =
wrap print_tree
let print_pair print_x print_y (x, y) =
tuple [ print_x x; print_y y ]
let print_char_list =
print_list print_char
let show_char_list =
wrap print_char_list
let print_char_string_list =
print_list (print_pair print_char print_string)
let show_char_string_list =
wrap print_char_string_list
let print_char_freq_list =
print_list (print_pair print_char print_int)
let show_char_freq_list =
wrap print_char_freq_list
let print_char_int =
print_pair print_char print_int
let show_char_int =
wrap print_char_int
(* -------------------------------------------------------------------------- *)
(* Determining whether a list is sorted. *)
(* If it is not sorted, we produce an inversion (a pair that is not sorted). *)
let rec is_sorted cmp xs =
match xs with
| []
| [_] ->
None
| x0 :: ((x1 :: _) as xs) ->
if cmp x0 x1 <= 0 then
is_sorted cmp xs
else
Some (x0, x1)
(* -------------------------------------------------------------------------- *)
(* Determining whether a string contains only '0' and '1' characters. *)
let string_for_all f s =
let exception Break in
try
for i = 0 to String.length s - 1 do
if not (f s.[i]) then raise Break
done;
true
with Break ->
false
let is_binary_char c =
match c with '0' | '1' -> true | _ -> false
let is_binary_string s =
string_for_all is_binary_char s
(* -------------------------------------------------------------------------- *)
Converting a single character to an 8 - character string of ' 0 ' and ' 1 ' .
[ write_char ] and [ read_char ] are in [ prelude.ml ] . The functions below
can be used for testing in the OCaml REPL .
can be used for testing in the OCaml REPL. *)
let encode_char (c : char) : string =
let b = Buffer.create 8 in
write_char b c;
Buffer.contents b
(* And back. *)
let next (s : string) : unit -> char =
let i = ref 0 in
fun () ->
s.[postincrement i]
let decode_char (data : data) : char =
read_char (next data)
(* -------------------------------------------------------------------------- *)
(* Grading [build_alphabet]. *)
We test [ build_alphabet ] in the context [ entries ] ( a function
defined in Prelude ) , which yields a sorted list of character-
frequency pairs .
defined in Prelude), which yields a sorted list of character-
frequency pairs. *)
let long_sentence =
"It is amazing that such a seemingly short sentence can be \
successfully compressed."
let inputs =
(* Short strings *)
Feat.(sample 20 4 Generate.string) @
(* Short strings where all characters have distinct frequency *)
List.map (Generate.distinct_frequency_string 'a') (up 2 10) @
(* A few long strings *)
"I am obviously right." ::
"The quick brown fox jumps over the lazy dog." ::
"alpha bravo alpha bravo bravo alpha bravo alpha alpha" ::
"Ça doit marcher avec des accents français aussi, eh oui, c'est énervant" ::
[]
let print_entries x =
apply "entries" [ parens x ]
let test_build_alphabet () =
section "Question 1" (
test_value_1_in_context
"build_alphabet" [%ty: text -> alphabet] Solution.build_alphabet
identity print_string
(* context: *) entries print_entries
(=) show_char_freq_list
inputs
)
In the following , we must be careful to apply [ build_tree ] only to
alphabets of two characters at least .
alphabets of two characters at least. *)
let inputs =
List.filter (fun input ->
List.length (entries (Solution.build_alphabet input)) >= 2
) inputs
(* -------------------------------------------------------------------------- *)
(* Grading [build_tree]. *)
(* Because printing an alphabet is impossible (it is a hash table), we prefer
to use strings as inputs, rather than alphabets. This means that we must
test the composition of [build_alphabet] and [build_tree], rather than
[build_tree] alone. *)
We can not expect the tree built by the student to have exactly the same
shape as ours ; the construction algorithm is nondeterministic , due to
possible draws between priorities . We first check that the leaves of the
tree form the alphabet . Then , we check that the tree is optimal , in the
sense that it yields an encoded input of minimal length .
shape as ours; the construction algorithm is nondeterministic, due to
possible draws between priorities. We first check that the leaves of the
tree form the alphabet. Then, we check that the tree is optimal, in the
sense that it yields an encoded input of minimal length. *)
let test_build_tree () =
let name = "build_tree" in
section "Question 2" (
grab [%ty: text -> alphabet] "build_alphabet" (fun build_alphabet ->
grab [%ty: alphabet -> tree] "build_tree" (fun build_tree ->
protect (fun () ->
Check 1 .
inputs |> List.iter begin fun input ->
let actual_behavior =
T.result (fun () ->
sort (leaves (build_tree (build_alphabet input)))
)
and expected_behavior =
T.result (fun () ->
Solution.(sort (leaves (build_tree (build_alphabet input))))
)
in
let print () =
piped_apply "sort" [
piped_apply "leaves" [
piped_apply "build_tree" [
piped_apply "build_alphabet" [
print_string input
]]]]
in
black_box_compare
(=) show_char_list
(incorrect name)
(wrap print) ()
actual_behavior
expected_behavior
end;
Check 2 .
inputs |> List.iter begin fun input ->
let actual_tree =
input
|> build_alphabet
|> build_tree
in
let actual_encoding_dictionary =
actual_tree
|> Solution.build_encoding_dictionary
in
let actual_encoded_input =
input
|> Solution.encode actual_encoding_dictionary
in
let actual_encoded_length =
actual_encoded_input
|> String.length
in
let expected_encoded_length = Solution.(
let encoding_dictionary =
input
|> build_alphabet
|> build_tree
|> build_encoding_dictionary
in
input
|> encode encoding_dictionary
|> String.length
) in
assert (expected_encoded_length <= actual_encoded_length);
if expected_encoded_length < actual_encoded_length then begin
let print_expr input =
piped_apply "build_tree" [
piped_apply "build_alphabet" [
print_string input
]]
in
fail (
incorrect name @
R.Text "The following expression:" ::
R.Break ::
R.Code (wrap print_expr input) ::
R.Break ::
R.Text "yields the following tree, which is suboptimal:" ::
R.Break ::
R.Code (show_tree actual_tree) ::
R.Break ::
R.Text (sprintf
"According to this tree, the input text \"%s\" \
is encoded as the binary string %s, \
whose length is %d bits, \
whereas, by using another tree, \
this input text can be encoded \
as a binary string of only %d bits."
input
actual_encoded_input
actual_encoded_length
expected_encoded_length
) ::
[]
)
end
end;
correct name
)))
)
(* -------------------------------------------------------------------------- *)
(* Grading [build_encoding_dictionary]. *)
let trees =
deepening Generate.all_trees_with_distinct_leaves 5
let test_build_encoding_dictionary () =
section "Question 3" (
test_value_1_in_context
"build_encoding_dictionary" [%ty: tree -> encoding_dictionary]
Solution.build_encoding_dictionary
identity print_tree
(* context: *) entries print_entries
(=) show_char_string_list
trees
)
(* -------------------------------------------------------------------------- *)
(* Grading [find]. *)
let triples : (data * int * tree) list =
trees |> flat_map (fun tree ->
paths tree |> flat_map (fun path ->
(path, 0, tree) ::
(path ^ "garbage", 0, tree) ::
("garbage" ^ path, 7, tree) ::
[]
)
)
let test_find () =
section "Question 4" (
test_value_3
"find" [%ty: data -> int -> tree -> char * int]
Solution.find
print_string print_int print_tree
show_char_int (=)
triples
)
(* -------------------------------------------------------------------------- *)
(* Testing that a student function [f] produces binary data when applied to
an argument [x]. *)
let test_binary_data msg f x show_f =
let actual_behavior = T.result (fun () -> f x) in
(* This is a modified [black_box_compare]. *)
match actual_behavior with
| Error TODO ->
raise TODO
| Error _ ->
fail (
msg @
R.Text "The following expression:" ::
R.Break ::
R.Code (show_f x) ::
R.Break ::
show_actual_behavior show_string actual_behavior
(* not explicitly said: raising an exception is invalid *)
)
| Ok data ->
if not (is_binary_string data) then
fail (
msg @
R.Text "The following expression:" ::
R.Break ::
R.Code (show_f x) ::
R.Break ::
show_actual_behavior show_string actual_behavior @
R.Break ::
R.Text "This is not binary data. \
No characters other than '0' and '1' must be used." ::
[]
)
(* -------------------------------------------------------------------------- *)
(* Grading [write] and [read]. *)
let print_write tree =
apply "write" [ parens (print_tree tree) ]
let show_write =
wrap print_write
let test_write_read () =
section "Question 5" (
grab [%ty: tree -> data] "write" (fun write ->
grab [%ty: data -> tree * int] "read" (fun read ->
protect (fun () ->
(* Check 0. Check that [write] does not crash and that its result is
binary data. *)
trees |> List.iter begin fun tree ->
test_binary_data
(incorrect "write")
write tree
show_write
end;
Check 1 . Test the first component of the result .
trees |> List.iter begin fun tree ->
let actual_behavior =
T.result (fun () ->
fst (read (write tree))
)
and expected_behavior =
Ok tree
in
let print () =
piped_apply "fst" [
piped_apply "read" [
piped_apply "write" [
print_tree tree
]]]
in
black_box_compare
(=) show_tree
something_is_wrong
(wrap print) ()
actual_behavior
expected_behavior;
end;
Check 2 . Test the second component of the result .
trees |> List.iter begin fun tree ->
let actual_behavior =
T.result (fun () ->
let data = write tree ^ "cookie" in
let i = snd (read data) in
String.sub data i 6
)
and expected_behavior =
Ok "cookie"
in
let print () =
let var = utf8string in
elet "data" (
infix_apply "^"
(apply "write" [ parens (print_tree tree) ])
(print_string "cookie")
)(
elet "i" (
apply "snd" [ parens_apply "read" [ var "data" ]]
)(
apply "String.sub" [ var "data"; var "i"; print_int 6 ]
)
)
in
black_box_compare
(=) show_string
something_is_wrong
(wrap print) ()
actual_behavior
expected_behavior
end;
correct2 "write" "read"
)))
)
(* -------------------------------------------------------------------------- *)
(* Grading [compress] and [decompress]. *)
let print_compress input =
piped_apply "compress" [ print_string input ]
let print_decompress_compress input =
piped_apply "decompress" [ print_compress input ]
let test_compress_decompress () =
section "Question 6" (
grab [%ty: text -> data] "compress" (fun compress ->
grab [%ty: data -> text] "decompress" (fun decompress ->
protect (fun () ->
(* Check 0. Check that [compress] does not crash and that its result is
binary data. *)
inputs |> List.iter begin fun input ->
test_binary_data
(incorrect "compress")
compress input
(wrap print_compress)
end;
Check 1 . The composition of [ compress ] and [ decompress ]
should be the identity .
should be the identity. *)
inputs |> List.iter begin fun input ->
let actual_behavior =
T.result (fun () ->
decompress (compress input)
)
and expected_behavior =
Ok input
in
black_box_compare
(=) show_string
something_is_wrong
(wrap print_decompress_compress) input
actual_behavior
expected_behavior
end;
Check 2 . On long sentences , some compression should achieved .
[ long_sentence ] |> List.iter begin fun input ->
let input_length (* in bits *) = 8 * String.length input in
let actual_result = compress input in
let actual_result_length (* in bits *) = String.length actual_result in
if not (actual_result_length < input_length) then
fail (
something_is_wrong @
R.Text "The following expression:" ::
R.Break ::
R.Code (wrap print_compress input) ::
R.Break ::
R.Text (
sprintf "produces a sequence of %d bits, \
whereas the original sentence occupies %d bits \
when represented as an ASCII string. \
No compression has been achieved! \
Perhaps your binary encoding of the dictionary \
is not compact enough?"
actual_result_length
input_length
) ::
[]
)
end;
(* OK. *)
correct2 "compress" "decompress"
)))
)
(* -------------------------------------------------------------------------- *)
(* Main. *)
let report () =
test_build_alphabet() @
test_build_tree() @
test_build_encoding_dictionary() @
test_find() @
test_write_read() @
test_compress_decompress() @
[]
let () =
T.set_result (T.ast_sanity_check code_ast report)
| null | https://raw.githubusercontent.com/ocaml-sf/learn-ocaml-corpus/7dcf4d72b49863a3e37e41b3c3097aa4c6101a69/exercises/fpottier/huffman/test.ml | ocaml | Determinism.
The auto-grader.
--------------------------------------------------------------------------
Some of the code below should move to separate library files.
--------------------------------------------------------------------------
Miscellaneous.
--------------------------------------------------------------------------
PPrintMini.
--------------------------------------------------------------------------
A type of integers with infinity.
with infinity
Addition of integers with infinity.
--------------------------------------------------------------------------
--------------------------------------------------------------------------
Retrieving or computing the space requirement of a document.
--------------------------------------------------------------------------
Document constructors.
--------------------------------------------------------------------------
Printing blank space (indentation characters).
--------------------------------------------------------------------------
The rendering engine maintains the following internal state.
For simplicity, the ribbon width is considered equal to the line
width; in other words, there is no ribbon width constraint.
For simplicity, the output channel is required to be an OCaml buffer.
It is stored within the [state] record.
The line width.
The current column.
The output buffer.
--------------------------------------------------------------------------
For simplicity, the rendering engine is *not* in tail-recursive style.
--------------------------------------------------------------------------
The engine's entry point.
--------------------------------------------------------------------------
Additions to PPrintMini.
Isolate the last argument.
Print.
--------------------------------------------------------------------------
An implementation of symbolic sequences.
if this fails, an overflow has occurred
Extract a list of at most [threshold] elements from the sequence [s].
If the sequence is short enough, keep of all its elements.
Otherwise, keep a randomly chosen sample.
--------------------------------------------------------------------------
A fixed point combinator.
--------------------------------------------------------------------------
MiniFeat.
enum (SymSeq.singleton x)
Convenience functions.
Extract a list of at most [threshold] elements of each size,
for every size up to [s] (included), from the enumeration [e].
--------------------------------------------------------------------------
When we fail, the exception carries a learn-ocaml report.
[section title report] encloses the report [report] within a section
entitled [title], producing a larger report.
This generic function takes as an argument the text of the message that
will be displayed. A message is a list of inline things.
This is a special case where the message is a singleton list containing
a single string. The string can be formatted using a printf format.
[protect f] evaluates [f()], which either returns normally and produces a
report, or raises [Fail] and produces a report. In either case, the report
is returned.
If an unexpected exception is raised, in student code or in grading code,
the exception is displayed as part of a failure report. (Ideally, grading
code should never raise an exception!) It is debatable whether one should
show just the name of the exception, or a full backtrace; I choose the
latter, on the basis that more information is always preferable.
[successful] tests whether a report is successful.
--------------------------------------------------------------------------
When doing black-box testing of a complete module, we are not testing just
one function in isolation, but a group of functions together. In that case,
the wording of the error message is somewhat different. Instead of saying
that a specific function is incorrect, we want to say that an expression
[expr] yields an incorrect result.
value comparison
exception comparison
Value equality and display, used to compare and show results.
The beginning of the error message. Use [something_is_wrong] or [incorrect name].
Expression display.
Actual behavior and expected behavior.
Allow [TODO] to escape and abort the whole test.
name and type of the function of interest:
reference implementation of this function:
input transformation function and input printer:
output transformation function and output printer:
observation equality test and observation printer:
list of inputs:
Beware: [print_input] must produce parentheses if necessary. Also,
[print_context] must enclose its argument in parentheses if necessary.
no context
--------------------------------------------------------------------------
List-based enumerations.
[up i j] is the list of the integers of [i] included up to [j] excluded.
[upk i j k] is [up i j @ k].
If [f i] is an enumeration, then [deepening f n] is the concatenation
of the enumerations [f 0, f 1, ... f n].
--------------------------------------------------------------------------
Printers.
A printer for strings.
A printer for integers.
A printer for characters.
A printer for options.
A printer for arrays.
A printer for lists.
--------------------------------------------------------------------------
Enumerating all paths into a tree.
--------------------------------------------------------------------------
A generator for trees.
A tree of size [n] has [n] nodes, therefore [n+1] leaves.
A generator for strings.
A generator for strings where each character has a distinct frequency.
--------------------------------------------------------------------------
A printer for trees.
Miscellaneous printers.
--------------------------------------------------------------------------
Determining whether a list is sorted.
If it is not sorted, we produce an inversion (a pair that is not sorted).
--------------------------------------------------------------------------
Determining whether a string contains only '0' and '1' characters.
--------------------------------------------------------------------------
And back.
--------------------------------------------------------------------------
Grading [build_alphabet].
Short strings
Short strings where all characters have distinct frequency
A few long strings
context:
--------------------------------------------------------------------------
Grading [build_tree].
Because printing an alphabet is impossible (it is a hash table), we prefer
to use strings as inputs, rather than alphabets. This means that we must
test the composition of [build_alphabet] and [build_tree], rather than
[build_tree] alone.
--------------------------------------------------------------------------
Grading [build_encoding_dictionary].
context:
--------------------------------------------------------------------------
Grading [find].
--------------------------------------------------------------------------
Testing that a student function [f] produces binary data when applied to
an argument [x].
This is a modified [black_box_compare].
not explicitly said: raising an exception is invalid
--------------------------------------------------------------------------
Grading [write] and [read].
Check 0. Check that [write] does not crash and that its result is
binary data.
--------------------------------------------------------------------------
Grading [compress] and [decompress].
Check 0. Check that [compress] does not crash and that its result is
binary data.
in bits
in bits
OK.
--------------------------------------------------------------------------
Main. | open Printf
let iter = List.iter
let map = List.map
module T = Test_lib
module R = Report
type report = R.t
let () = Random.init 0
let postincrement c =
let n = !c in
c := n + 1;
n
type requirement =
Infinity is encoded as [ max_int ] .
let infinity : requirement =
max_int
let (++) (x : requirement) (y : requirement) : requirement =
if x = infinity || y = infinity then
infinity
else
x + y
Comparison between an integer with infinity and a normal integer .
let (<==) (x : requirement) (y : int) =
x <= y
The type of documents . See [ ] for documentation .
type document =
| Empty
| FancyString of string * int * int * int
| Blank of int
| IfFlat of document * document
| HardLine
| Cat of requirement * document * document
| Nest of requirement * int * document
| Group of requirement * document
let rec requirement = function
| Empty ->
0
| FancyString (_, _, _, len)
| Blank len ->
len
| IfFlat (doc1, _) ->
requirement doc1
| HardLine ->
infinity
| Cat (req, _, _)
| Nest (req, _, _)
| Group (req, _) ->
req
let empty =
Empty
let fancysubstring s ofs len apparent_length =
if len = 0 then
empty
else
FancyString (s, ofs, len, apparent_length)
let fancystring s apparent_length =
fancysubstring s 0 (String.length s) apparent_length
let utf8_length s =
let rec length_aux s c i =
if i >= String.length s then c else
let n = Char.code (String.unsafe_get s i) in
let k =
if n < 0x80 then 1 else
if n < 0xe0 then 2 else
if n < 0xf0 then 3 else 4
in
length_aux s (c + 1) (i + k)
in
length_aux s 0 0
let utf8string s =
fancystring s (utf8_length s)
let utf8format f =
ksprintf utf8string f
let char c =
assert (c <> '\n');
fancystring (String.make 1 c) 1
let space =
char ' '
let semicolon =
char ';'
let hardline =
HardLine
let blank n =
match n with
| 0 ->
empty
| 1 ->
space
| _ ->
Blank n
let ifflat doc1 doc2 =
match doc1 with
| IfFlat (doc1, _)
| doc1 ->
IfFlat (doc1, doc2)
let internal_break i =
ifflat (blank i) hardline
let break0 =
internal_break 0
let break1 =
internal_break 1
let break i =
match i with
| 0 ->
break0
| 1 ->
break1
| _ ->
internal_break i
let (^^) x y =
match x, y with
| Empty, _ ->
y
| _, Empty ->
x
| _, _ ->
Cat (requirement x ++ requirement y, x, y)
let nest i x =
assert (i >= 0);
Nest (requirement x, i, x)
let group x =
let req = requirement x in
if req = infinity then
x
else
Group (req, x)
let blank_length =
80
let blank_buffer =
String.make blank_length ' '
let rec blanks output n =
if n <= 0 then
()
else if n <= blank_length then
Buffer.add_substring output blank_buffer 0 n
else begin
Buffer.add_substring output blank_buffer 0 blank_length;
blanks output (n - blank_length)
end
type state =
{
width: int;
mutable column: int;
mutable output: Buffer.t;
}
let rec pretty state (indent : int) (flatten : bool) doc =
match doc with
| Empty ->
()
| FancyString (s, ofs, len, apparent_length) ->
Buffer.add_substring state.output s ofs len;
state.column <- state.column + apparent_length
| Blank n ->
blanks state.output n;
state.column <- state.column + n
| HardLine ->
assert (not flatten);
Buffer.add_char state.output '\n';
blanks state.output indent;
state.column <- indent
| IfFlat (doc1, doc2) ->
pretty state indent flatten (if flatten then doc1 else doc2)
| Cat (_, doc1, doc2) ->
pretty state indent flatten doc1;
pretty state indent flatten doc2
| Nest (_, j, doc) ->
pretty state (indent + j) flatten doc
| Group (req, doc) ->
let flatten = flatten || state.column ++ req <== state.width in
pretty state indent flatten doc
let pretty width doc =
let output = Buffer.create 512 in
let state = { width; column = 0; output } in
pretty state 0 false doc;
Buffer.contents output
let separate (sep : 'a) (xs : 'a list) : 'a list =
match xs with
| [] ->
[]
| x :: xs ->
x :: List.flatten (List.map (fun x -> [sep; x]) xs)
let concat (docs : document list) : document =
List.fold_right (^^) docs empty
let comma =
utf8string "," ^^ break 1
let commas docs =
concat (separate comma docs)
let semi =
utf8string ";" ^^ break 1
let semis docs =
concat (separate semi docs)
let int i =
utf8format "%d" i
let block b doc =
nest 2 (break b ^^ doc) ^^ break b
let parens doc =
utf8string "(" ^^ block 0 doc ^^ utf8string ")"
let brackets doc =
utf8string "[" ^^ block 0 doc ^^ utf8string "]"
let ocaml_array_brackets doc =
utf8string "[| " ^^ block 0 doc ^^ utf8string "|]"
let tuple docs =
group (parens (commas docs))
let list docs =
group (brackets (semis docs))
let construct label docs =
match docs with
| [] ->
utf8string label
| _ ->
utf8string label ^^ space ^^ tuple docs
let flow docs =
match docs with
| [] ->
[]
| doc :: docs ->
doc :: map (fun doc -> group (break 1) ^^ doc) docs
let raw_apply docs =
group (concat (flow docs))
let apply f docs =
raw_apply (utf8string f :: docs)
let parens_apply f docs =
parens (apply f docs)
let piped_apply f docs =
assert (List.length docs > 0);
let docs = List.rev docs in
let doc, docs = List.hd docs, List.rev (List.tl docs) in
group (doc ^^ break 1 ^^ utf8string "|>" ^^ space ^^ apply f docs)
let infix_apply op doc1 doc2 =
group (
group (doc1 ^^ break 1 ^^ utf8string op) ^^ break 1 ^^
doc2
)
let elet x doc1 doc2 =
group (
group (
utf8format "let %s =" x ^^
block 1 doc1 ^^
utf8string "in"
) ^^ break 1 ^^
doc2
)
let wrap (print : 'a -> document) : 'a -> string =
fun x -> pretty 70 (group (print x))
module SymSeq = struct
type _ seq =
| Empty : 'a seq
| Singleton: 'a -> 'a seq
| Sum : int * 'a seq * 'a seq -> 'a seq
| Product : int * 'a seq * 'b seq -> ('a * 'b) seq
| Map : int * ('a -> 'b) * 'a seq -> 'b seq
exception OutOfBounds
let length (type a) (s : a seq) : int =
match s with
| Empty ->
0
| Singleton _ ->
1
| Sum (length, _, _) ->
length
| Product (length, _, _) ->
length
| Map (length, _, _) ->
length
let is_empty s =
length s = 0
let empty =
Empty
let singleton x =
Singleton x
let check length =
length
let sum s1 s2 =
if is_empty s1 then s2
else if is_empty s2 then s1
else Sum (check (length s1 + length s2), s1, s2)
let bigsum ss =
List.fold_left sum empty ss
let product s1 s2 =
if is_empty s1 || is_empty s2 then
empty
else
Product (check (length s1 * length s2), s1, s2)
let map phi s =
if is_empty s then
empty
else
Map (length s, phi, s)
let rec get : type a . a seq -> int -> a =
fun s i ->
match s with
| Empty ->
raise OutOfBounds
| Singleton x ->
if i = 0 then x else raise OutOfBounds
| Sum (_, s1, s2) ->
let n1 = length s1 in
if i < n1 then get s1 i
else get s2 (i - n1)
| Product (_, s1, s2) ->
let q, r = i / length s2, i mod length s2 in
get s1 q, get s2 r
| Map (_, phi, s) ->
phi (get s i)
let rec foreach : type a . a seq -> (a -> unit) -> unit =
fun s k ->
match s with
| Empty ->
()
| Singleton x ->
k x
| Sum (_, s1, s2) ->
foreach s1 k;
foreach s2 k
| Product (_, s1, s2) ->
foreach s1 (fun x1 ->
foreach s2 (fun x2 ->
k (x1, x2)
)
)
| Map (_, phi, s) ->
foreach s (fun x -> k (phi x))
let elements (s : 'a seq) : 'a list =
let xs = ref [] in
foreach s (fun x -> xs := x :: !xs);
List.rev !xs
For some reason , [ Random.int ] stops working at [ 2 ^ 30 ] .
let rec random_int n =
let threshold = 1 lsl 30 in
if n < threshold then
Random.int n
else
failwith "Can't sample over more than 2^30 elements."
let sample threshold (s : 'a seq) : 'a list =
if length s <= threshold then
elements s
else
let xs = ref [] in
for i = 1 to threshold do
let i = random_int (length s) in
let x = get s i in
xs := x :: !xs
done;
!xs
end
type 'a seq =
'a SymSeq.seq
let fix : type a b . ((a -> b) -> (a -> b)) -> (a -> b) =
fun ff ->
let table = Hashtbl.create 128 in
let rec f (x : a) : b =
try
Hashtbl.find table x
with Not_found ->
let y = ff f x in
Hashtbl.add table x y;
y
in
f
let curry f x y = f (x, y)
let uncurry f (x, y) = f x y
let fix2 : type a b c . ((a -> b -> c) -> (a -> b -> c)) -> (a -> b -> c) =
fun ff ->
let ff f = uncurry (ff (curry f)) in
curry (fix ff)
module Feat = struct
Core combinators .
type 'a enum =
int -> 'a SymSeq.seq
let empty : 'a enum =
fun _s ->
SymSeq.empty
let zero =
empty
let enum (xs : 'a SymSeq.seq) : 'a enum =
fun s ->
if s = 0 then xs else SymSeq.empty
let just (x : 'a) : 'a enum =
fun s ->
if s = 0 then SymSeq.singleton x else SymSeq.empty
let pay (enum : 'a enum) : 'a enum =
fun s ->
if s = 0 then SymSeq.empty else enum (s-1)
let sum (enum1 : 'a enum) (enum2 : 'a enum) : 'a enum =
fun s ->
SymSeq.sum (enum1 s) (enum2 s)
let ( ++ ) =
sum
let rec _up i j =
if i <= j then
i :: _up (i + 1) j
else
[]
let product (enum1 : 'a enum) (enum2 : 'b enum) : ('a * 'b) enum =
fun s ->
SymSeq.bigsum (
List.map (fun s1 ->
let s2 = s - s1 in
SymSeq.product (enum1 s1) (enum2 s2)
) (_up 0 s)
)
let ( ** ) =
product
let balanced_product (enum1 : 'a enum) (enum2 : 'b enum) : ('a * 'b) enum =
fun s ->
if s mod 2 = 0 then
let s = s / 2 in
SymSeq.product (enum1 s) (enum2 s)
else
let s = s / 2 in
SymSeq.sum
(SymSeq.product (enum1 s) (enum2 (s+1)))
(SymSeq.product (enum1 (s+1)) (enum2 s))
let ( *-* ) =
balanced_product
let map (phi : 'a -> 'b) (enum : 'a enum) : 'b enum =
fun s ->
SymSeq.map phi (enum s)
let finite (xs : 'a list) : 'a enum =
List.fold_left (++) zero (List.map just xs)
let bool : bool enum =
just false ++ just true
let list (elem : 'a enum) : 'a list enum =
let cons (x, xs) = x :: xs in
fix (fun list ->
just [] ++ pay (map cons (elem ** list))
)
let nonempty_list (elem : 'a enum) : 'a list enum =
let cons (x, xs) = x :: xs in
map cons (elem ** list elem)
let sample threshold s (e : 'a enum) : 'a list =
List.flatten (
List.map (fun i ->
SymSeq.sample threshold (e i)
) (_up 0 s)
)
end
type 'a enum =
'a Feat.enum
Generic testing utilities .
exception Fail of report
let section title report : report =
[R.Section ([R.Text title], report)]
let fail (text : R.inline list) =
let report = [R.Message (text, R.Failure)] in
raise (Fail report)
let fail_text format =
Printf.ksprintf (fun s -> fail [R.Text s]) format
let protect f =
try
T.run_timeout f
with
| Fail report ->
report
| TODO ->
let text = [
R.Text "Not yet implemented."
] in
let report = [R.Message (text, R.Failure)] in
report
| (e : exn) ->
let text = [
R.Text "The following exception is raised and never caught:";
R.Break;
R.Output (Printexc.to_string e);
R.Output (Printexc.get_backtrace());
] in
let report = [R.Message (text, R.Failure)] in
report
let successful_status = function
| R.Success _
| R.Warning
| R.Informative
| R.Important ->
true
| R.Failure ->
false
let rec successful_item = function
| R.Section (_, r) ->
successful r
| R.Message (_, status) ->
successful_status status
and successful (r : report) =
List.for_all successful_item r
let (-@>) (r : report) (f : unit -> report) : report =
if successful r then
r @ f()
else
r
Generic test functions .
let grab ty name k =
T.test_value (T.lookup_student ty name) k
let test_value_0 name ty reference eq =
grab ty name (fun candidate ->
protect (fun () ->
if not (eq candidate reference) then
fail [
R.Code name; R.Text "is incorrect.";
];
let message = [ R.Code name; R.Text "is correct."; ] in
[ R.Message (message, R.Success 1) ]
)
)
let correct name =
let message = [ R.Code name; R.Text "seems correct."; ] in
[ R.Message (message, R.Success 1) ]
let correct2 name1 name2 =
let message = [ R.Code name1; R.Text "and"; R.Code name2; R.Text "seem correct."; ] in
[ R.Message (message, R.Success 1) ]
let eq_behavior eq_value actual_behavior expected_behavior =
match actual_behavior, expected_behavior with
| Ok actual, Ok expected ->
| Error actual, Error expected ->
| Ok _, Error _
| Error _, Ok _ ->
false
let show_actual_behavior show_value behavior =
match behavior with
| Ok v ->
R.Text "produces the following result:" ::
R.Output (show_value v) ::
[]
| Error e ->
R.Text "raises the following exception:" ::
R.Output (Printexc.to_string e) ::
[]
let show_expected_behavior show_value behavior =
match behavior with
| Ok v ->
R.Text "This is invalid. Producing the following result is valid:" ::
R.Output (show_value v) ::
[]
| Error e ->
R.Text "This is invalid. Raising the following exception is valid:" ::
R.Output (Printexc.to_string e) ::
[]
let something_is_wrong =
R.Text "Something is wrong." ::
[]
let incorrect name =
R.Code name :: R.Text "is incorrect." ::
R.Break ::
[]
let black_box_compare
eq_value show_value
announcement
show_expr expr
actual_behavior
expected_behavior
=
if actual_behavior = Error TODO then
raise TODO
else if not (eq_behavior eq_value actual_behavior expected_behavior) then
fail (
announcement @
R.Text "The following expression:" ::
R.Break ::
R.Code (show_expr expr) ::
R.Break ::
show_actual_behavior show_value actual_behavior @
show_expected_behavior show_value expected_behavior
)
let test_value_1_in_context
name ty
reference
make_input print_input
context print_context
eq show_observation
tests
=
grab ty name (fun candidate ->
protect (fun () ->
tests |> List.iter (fun x ->
let actual_behavior =
T.result (fun () ->
context (candidate (make_input x))
)
and expected_behavior =
T.result (fun () ->
context (reference (make_input x))
)
in
let print () =
print_context (apply name [ print_input x ])
in
black_box_compare
eq show_observation
(incorrect name)
(wrap print) ()
actual_behavior
expected_behavior
);
correct name
)
)
let identity x = x
let test_value_1 name ty reference printx eqy showy tests =
test_value_1_in_context
name ty reference
identity printx
eqy showy tests
let test_value_2 name ty reference printx1 printx2 showy eqy tests =
grab ty name (fun candidate ->
protect (fun () ->
tests |> List.iter (fun ((x1, x2) as x) ->
let actual_behavior = T.result (fun () -> candidate x1 x2)
and expected_behavior = T.result (fun () -> reference x1 x2) in
let print_expr () =
apply name [ printx1 x1; printx2 x2 ]
beware : [ printx1 ] and [ ] must produce parentheses
if necessary
if necessary *)
in
black_box_compare
eqy showy
(incorrect name)
(wrap print_expr) ()
actual_behavior
expected_behavior
);
correct name
)
)
let test_value_3 name ty reference printx1 printx2 printx3 showy eqy tests =
grab ty name (fun candidate ->
protect (fun () ->
tests |> List.iter (fun ((x1, x2, x3) as x) ->
let actual_behavior = T.result (fun () -> candidate x1 x2 x3)
and expected_behavior = T.result (fun () -> reference x1 x2 x3) in
let print_expr () =
apply name [ printx1 x1; printx2 x2; printx3 x3 ]
beware : [ printx1 ] , etc . must produce parentheses
if necessary
if necessary *)
in
black_box_compare
eqy showy
(incorrect name)
(wrap print_expr) ()
actual_behavior
expected_behavior
);
correct name
)
)
let flat_map f xss =
List.flatten (List.map f xss)
let rec upk i j k =
if i < j then
i :: upk (i + 1) j k
else
k
let up i j =
upk i j []
[ pairs xs ys ] is the list of all pairs [ x , y ] where [ x ] is drawn from [ xs ]
and [ y ] is drawn from [ ys ] . In other words , it is the Cartesian product of
the lists [ xs ] and [ ys ] .
and [y] is drawn from [ys]. In other words, it is the Cartesian product of
the lists [xs] and [ys]. *)
let pairs xs ys =
xs |> flat_map (fun x ->
ys |> flat_map (fun y ->
[x, y]
)
)
[ split n f ] enumerates all manners of splitting [ n ] into [ n1 + n2 ] , where
[ n1 ] and [ n2 ] can be zero . For each such split , the enumeration [ f n1 n2 ]
is produced .
[n1] and [n2] can be zero. For each such split, the enumeration [f n1 n2]
is produced. *)
let split n f =
flat_map (fun n1 ->
let n2 = n - n1 in
f n1 n2
) (up 0 (n+1))
let deepening (f : int -> 'a list) (n : int) : 'a list =
flat_map f (up 0 (n+1))
let show_string s =
sprintf "\"%s\"" (String.escaped s)
let print_string s =
utf8string (show_string s)
let print_int =
int
let show_int i =
sprintf "%d" i
let show_char c =
sprintf "'%s'" (Char.escaped c)
let print_char c =
utf8string (show_char c)
A printer for Booleans .
let show_bool b =
if b then "true" else "false"
let print_bool b =
utf8string (show_bool b)
let print_option print = function
| None ->
utf8string "None"
| Some x ->
construct "Some" [ print x ]
let print_array print_element a =
group (ocaml_array_brackets (concat (
a |> Array.map (fun x ->
print_element x ^^ semicolon ^^ break 1
) |> Array.to_list
)))
let print_list print_element xs =
list (map print_element xs)
let print_list_int =
print_list print_int
let show_list_int =
wrap print_list_int
let rec paths prefix (t : tree) accu =
match t with
| Leaf _ ->
prefix :: accu
| Node (t0, t1) ->
paths (prefix ^ "0") t0 (
paths (prefix ^ "1") t1
accu
)
let paths t =
paths "" t []
We want to generate trees with distinct leaves . The easiest way of doing so
seems to be to first generate trees with arbitrary data at the leaves , then
( in a separate pass ) populate the leaves with distinct characters .
seems to be to first generate trees with arbitrary data at the leaves, then
(in a separate pass) populate the leaves with distinct characters. *)
module Generate = struct
open Feat
let node (t1, t2) =
Node (t1, t2)
let rec tree : tree enum =
fix (fun tree ->
just (Leaf 'z') ++
pay (map node (tree ** tree))
)
let decorate tree =
let c = ref 0 in
let next () : char =
Char.chr (postincrement c + Char.code 'a')
in
let rec decorate tree =
match tree with
| Leaf _ ->
Leaf (next())
| Node (t0, t1) ->
Node (decorate t0, decorate t1)
in
decorate tree
let all_trees_with_distinct_leaves n =
Generate all trees of size [ n ] , then decorate them . Note that we
do not need to enumerate all permutations of characters at the
leaves ; one permutation suffices to exercise the student 's code .
do not need to enumerate all permutations of characters at the
leaves; one permutation suffices to exercise the student's code. *)
SymSeq.elements (tree n) |> List.map decorate
let character : string enum =
finite [ "a"; "b"; "c"; "d" ]
let glue : string list -> string =
String.concat ""
let string : string enum =
list character |> map glue
let successor (c : char) : char =
Char.chr (Char.code c + 1)
let rec distinct_frequency_string (start : char) n =
if n = 0 then
""
else
String.make n start ^
distinct_frequency_string (successor start) (n - 1)
end
let rec print_tree tree =
match tree with
| Leaf c ->
utf8string "Leaf" ^^ space ^^ print_char c
| Node (t0, t1) ->
construct "Node" [ print_tree t0; print_tree t1 ]
let show_tree =
wrap print_tree
let print_pair print_x print_y (x, y) =
tuple [ print_x x; print_y y ]
let print_char_list =
print_list print_char
let show_char_list =
wrap print_char_list
let print_char_string_list =
print_list (print_pair print_char print_string)
let show_char_string_list =
wrap print_char_string_list
let print_char_freq_list =
print_list (print_pair print_char print_int)
let show_char_freq_list =
wrap print_char_freq_list
let print_char_int =
print_pair print_char print_int
let show_char_int =
wrap print_char_int
let rec is_sorted cmp xs =
match xs with
| []
| [_] ->
None
| x0 :: ((x1 :: _) as xs) ->
if cmp x0 x1 <= 0 then
is_sorted cmp xs
else
Some (x0, x1)
let string_for_all f s =
let exception Break in
try
for i = 0 to String.length s - 1 do
if not (f s.[i]) then raise Break
done;
true
with Break ->
false
let is_binary_char c =
match c with '0' | '1' -> true | _ -> false
let is_binary_string s =
string_for_all is_binary_char s
Converting a single character to an 8 - character string of ' 0 ' and ' 1 ' .
[ write_char ] and [ read_char ] are in [ prelude.ml ] . The functions below
can be used for testing in the OCaml REPL .
can be used for testing in the OCaml REPL. *)
let encode_char (c : char) : string =
let b = Buffer.create 8 in
write_char b c;
Buffer.contents b
let next (s : string) : unit -> char =
let i = ref 0 in
fun () ->
s.[postincrement i]
let decode_char (data : data) : char =
read_char (next data)
We test [ build_alphabet ] in the context [ entries ] ( a function
defined in Prelude ) , which yields a sorted list of character-
frequency pairs .
defined in Prelude), which yields a sorted list of character-
frequency pairs. *)
let long_sentence =
"It is amazing that such a seemingly short sentence can be \
successfully compressed."
let inputs =
Feat.(sample 20 4 Generate.string) @
List.map (Generate.distinct_frequency_string 'a') (up 2 10) @
"I am obviously right." ::
"The quick brown fox jumps over the lazy dog." ::
"alpha bravo alpha bravo bravo alpha bravo alpha alpha" ::
"Ça doit marcher avec des accents français aussi, eh oui, c'est énervant" ::
[]
let print_entries x =
apply "entries" [ parens x ]
let test_build_alphabet () =
section "Question 1" (
test_value_1_in_context
"build_alphabet" [%ty: text -> alphabet] Solution.build_alphabet
identity print_string
(=) show_char_freq_list
inputs
)
In the following , we must be careful to apply [ build_tree ] only to
alphabets of two characters at least .
alphabets of two characters at least. *)
let inputs =
List.filter (fun input ->
List.length (entries (Solution.build_alphabet input)) >= 2
) inputs
We can not expect the tree built by the student to have exactly the same
shape as ours ; the construction algorithm is nondeterministic , due to
possible draws between priorities . We first check that the leaves of the
tree form the alphabet . Then , we check that the tree is optimal , in the
sense that it yields an encoded input of minimal length .
shape as ours; the construction algorithm is nondeterministic, due to
possible draws between priorities. We first check that the leaves of the
tree form the alphabet. Then, we check that the tree is optimal, in the
sense that it yields an encoded input of minimal length. *)
let test_build_tree () =
let name = "build_tree" in
section "Question 2" (
grab [%ty: text -> alphabet] "build_alphabet" (fun build_alphabet ->
grab [%ty: alphabet -> tree] "build_tree" (fun build_tree ->
protect (fun () ->
Check 1 .
inputs |> List.iter begin fun input ->
let actual_behavior =
T.result (fun () ->
sort (leaves (build_tree (build_alphabet input)))
)
and expected_behavior =
T.result (fun () ->
Solution.(sort (leaves (build_tree (build_alphabet input))))
)
in
let print () =
piped_apply "sort" [
piped_apply "leaves" [
piped_apply "build_tree" [
piped_apply "build_alphabet" [
print_string input
]]]]
in
black_box_compare
(=) show_char_list
(incorrect name)
(wrap print) ()
actual_behavior
expected_behavior
end;
Check 2 .
inputs |> List.iter begin fun input ->
let actual_tree =
input
|> build_alphabet
|> build_tree
in
let actual_encoding_dictionary =
actual_tree
|> Solution.build_encoding_dictionary
in
let actual_encoded_input =
input
|> Solution.encode actual_encoding_dictionary
in
let actual_encoded_length =
actual_encoded_input
|> String.length
in
let expected_encoded_length = Solution.(
let encoding_dictionary =
input
|> build_alphabet
|> build_tree
|> build_encoding_dictionary
in
input
|> encode encoding_dictionary
|> String.length
) in
assert (expected_encoded_length <= actual_encoded_length);
if expected_encoded_length < actual_encoded_length then begin
let print_expr input =
piped_apply "build_tree" [
piped_apply "build_alphabet" [
print_string input
]]
in
fail (
incorrect name @
R.Text "The following expression:" ::
R.Break ::
R.Code (wrap print_expr input) ::
R.Break ::
R.Text "yields the following tree, which is suboptimal:" ::
R.Break ::
R.Code (show_tree actual_tree) ::
R.Break ::
R.Text (sprintf
"According to this tree, the input text \"%s\" \
is encoded as the binary string %s, \
whose length is %d bits, \
whereas, by using another tree, \
this input text can be encoded \
as a binary string of only %d bits."
input
actual_encoded_input
actual_encoded_length
expected_encoded_length
) ::
[]
)
end
end;
correct name
)))
)
let trees =
deepening Generate.all_trees_with_distinct_leaves 5
let test_build_encoding_dictionary () =
section "Question 3" (
test_value_1_in_context
"build_encoding_dictionary" [%ty: tree -> encoding_dictionary]
Solution.build_encoding_dictionary
identity print_tree
(=) show_char_string_list
trees
)
let triples : (data * int * tree) list =
trees |> flat_map (fun tree ->
paths tree |> flat_map (fun path ->
(path, 0, tree) ::
(path ^ "garbage", 0, tree) ::
("garbage" ^ path, 7, tree) ::
[]
)
)
let test_find () =
section "Question 4" (
test_value_3
"find" [%ty: data -> int -> tree -> char * int]
Solution.find
print_string print_int print_tree
show_char_int (=)
triples
)
let test_binary_data msg f x show_f =
let actual_behavior = T.result (fun () -> f x) in
match actual_behavior with
| Error TODO ->
raise TODO
| Error _ ->
fail (
msg @
R.Text "The following expression:" ::
R.Break ::
R.Code (show_f x) ::
R.Break ::
show_actual_behavior show_string actual_behavior
)
| Ok data ->
if not (is_binary_string data) then
fail (
msg @
R.Text "The following expression:" ::
R.Break ::
R.Code (show_f x) ::
R.Break ::
show_actual_behavior show_string actual_behavior @
R.Break ::
R.Text "This is not binary data. \
No characters other than '0' and '1' must be used." ::
[]
)
let print_write tree =
apply "write" [ parens (print_tree tree) ]
let show_write =
wrap print_write
let test_write_read () =
section "Question 5" (
grab [%ty: tree -> data] "write" (fun write ->
grab [%ty: data -> tree * int] "read" (fun read ->
protect (fun () ->
trees |> List.iter begin fun tree ->
test_binary_data
(incorrect "write")
write tree
show_write
end;
Check 1 . Test the first component of the result .
trees |> List.iter begin fun tree ->
let actual_behavior =
T.result (fun () ->
fst (read (write tree))
)
and expected_behavior =
Ok tree
in
let print () =
piped_apply "fst" [
piped_apply "read" [
piped_apply "write" [
print_tree tree
]]]
in
black_box_compare
(=) show_tree
something_is_wrong
(wrap print) ()
actual_behavior
expected_behavior;
end;
Check 2 . Test the second component of the result .
trees |> List.iter begin fun tree ->
let actual_behavior =
T.result (fun () ->
let data = write tree ^ "cookie" in
let i = snd (read data) in
String.sub data i 6
)
and expected_behavior =
Ok "cookie"
in
let print () =
let var = utf8string in
elet "data" (
infix_apply "^"
(apply "write" [ parens (print_tree tree) ])
(print_string "cookie")
)(
elet "i" (
apply "snd" [ parens_apply "read" [ var "data" ]]
)(
apply "String.sub" [ var "data"; var "i"; print_int 6 ]
)
)
in
black_box_compare
(=) show_string
something_is_wrong
(wrap print) ()
actual_behavior
expected_behavior
end;
correct2 "write" "read"
)))
)
let print_compress input =
piped_apply "compress" [ print_string input ]
let print_decompress_compress input =
piped_apply "decompress" [ print_compress input ]
let test_compress_decompress () =
section "Question 6" (
grab [%ty: text -> data] "compress" (fun compress ->
grab [%ty: data -> text] "decompress" (fun decompress ->
protect (fun () ->
inputs |> List.iter begin fun input ->
test_binary_data
(incorrect "compress")
compress input
(wrap print_compress)
end;
Check 1 . The composition of [ compress ] and [ decompress ]
should be the identity .
should be the identity. *)
inputs |> List.iter begin fun input ->
let actual_behavior =
T.result (fun () ->
decompress (compress input)
)
and expected_behavior =
Ok input
in
black_box_compare
(=) show_string
something_is_wrong
(wrap print_decompress_compress) input
actual_behavior
expected_behavior
end;
Check 2 . On long sentences , some compression should achieved .
[ long_sentence ] |> List.iter begin fun input ->
let actual_result = compress input in
if not (actual_result_length < input_length) then
fail (
something_is_wrong @
R.Text "The following expression:" ::
R.Break ::
R.Code (wrap print_compress input) ::
R.Break ::
R.Text (
sprintf "produces a sequence of %d bits, \
whereas the original sentence occupies %d bits \
when represented as an ASCII string. \
No compression has been achieved! \
Perhaps your binary encoding of the dictionary \
is not compact enough?"
actual_result_length
input_length
) ::
[]
)
end;
correct2 "compress" "decompress"
)))
)
let report () =
test_build_alphabet() @
test_build_tree() @
test_build_encoding_dictionary() @
test_find() @
test_write_read() @
test_compress_decompress() @
[]
let () =
T.set_result (T.ast_sanity_check code_ast report)
|
97b36081a2f86882dadb257fe406ae9dd07f506299c473c9a8ac5e5557bf7ede | i-am-tom/haskell-exercises | KindSignatures.hs | # LANGUAGE FlexibleInstances #
{-# LANGUAGE KindSignatures #-}
3 , in which our heroes discover
which they can help us. We'll see -} where {- we need them, and where they're
just good documentation.. -}
---
We are , hopefully , familiar with the notion of /types/ : @3@ is a value of
type @Int@ , @Nothing@ is a value of @Maybe ( IO String)@ , and so on . However ,
there is also a notion of types /for types/ : kinds .
In our standard , everyday usage , all the types we use have the same kind :
' * ' , which we 'll pronounce ' Type ' . In fact , we can use ' Type ' instead of ' * '
by using the following import .
We are, hopefully, familiar with the notion of /types/: @3@ is a value of
type @Int@, @Nothing@ is a value of @Maybe (IO String)@, and so on. However,
there is also a notion of types /for types/: kinds.
In our standard, everyday usage, all the types we use have the same kind:
'*', which we'll pronounce 'Type'. In fact, we can use 'Type' instead of '*'
by using the following import.
-}
import Data.Kind -- Type = (*)
{-
This is a good habit to adopt, as '*' is going to be deprecated soon, in
favour of the more explicit and (hopefully) clear 'Type'. Now, we know all
sorts of things of kind 'Type':
-}
class OfKindType a
instance OfKindType Bool
instance OfKindType String -- Which extension did we need
instance OfKindType (Maybe (IO ())) -- to get /these/ to compile?
We can start with an intuition that the ' Type ' kind is inhabited by /things
with a runtime value/. This is n't 100 % accurate , but gives us somewhere to
start : all our /values/ have a type that has a kind of ' Type ' . We can see ,
for example , that @Maybe Int@ is of kind ' Type ' . ' Maybe ' is a funny one ,
though , right ? We could think of it as a " type - level function " :
@
Maybe : : Type - > Type
@
In other words , ' Maybe ' on its own is n't a type - it 's a type /constructor/.
" A ' Maybe ' of ? " , the type - checker asks . ' Maybe Int ' is a type , and
' Maybe ( ) ' is a type , but ' Maybe ' is n't . We can say that ' Maybe ' has kind
' Type - > Type ' because it 's like a function that , given a type , gives us a
type . For example , given ' Int ' , we get ' Maybe Int ' . Given ' ' , we get
' Maybe ' , and so on .
It is because of this that we ca n't write the following instance :
We can start with an intuition that the 'Type' kind is inhabited by /things
with a runtime value/. This isn't 100% accurate, but gives us somewhere to
start: all our /values/ have a type that has a kind of 'Type'. We can see,
for example, that @Maybe Int@ is of kind 'Type'. 'Maybe' is a funny one,
though, right? We could think of it as a "type-level function":
@
Maybe :: Type -> Type
@
In other words, 'Maybe' on its own isn't a type - it's a type /constructor/.
"A 'Maybe' of /what/?", the type-checker asks. 'Maybe Int' is a type, and
'Maybe ()' is a type, but 'Maybe' isn't. We can say that 'Maybe' has kind
'Type -> Type' because it's like a function that, given a type, gives us a
type. For example, given 'Int', we get 'Maybe Int'. Given 'Bool', we get
'Maybe Bool', and so on.
It is because of this that we can't write the following instance:
-}
instance OfKindType Maybe
• Expecting one more argument to ‘ Maybe ’
Expected a type , but ‘ Maybe ’ has kind ‘ * - > * ’
• In the first argument of ‘ OfKindType ’ , namely ‘ Maybe ’
In the instance declaration for ‘ OfKindType Maybe ’
The big problem here is that , in the absence of a better idea , GHC will
assume that a typeclass parameter is of kind ' Type ' .
How do we tell it otherwise ?
One way is to give GHC more information about our type by filling in method
signatures for our class .
For example , let 's take a look at a simplfied definition for the Functor class :
• Expecting one more argument to ‘Maybe’
Expected a type, but ‘Maybe’ has kind ‘* -> *’
• In the first argument of ‘OfKindType’, namely ‘Maybe’
In the instance declaration for ‘OfKindType Maybe’
The big problem here is that, in the absence of a better idea, GHC will
assume that a typeclass parameter is of kind 'Type'.
How do we tell it otherwise?
One way is to give GHC more information about our type by filling in method
signatures for our class.
For example, let's take a look at a simplfied definition for the Functor class:
-}
class Functor f where
fmap :: (a -> b) -> f a -> f b
Although @f@ is on its own here in the class definition , if we take a closer
look at the signature for @fmap@ we can see that never appears on its
own , but it sits right in front of another type variable every time it shows
up : @f a@ and
This information alone is enough for GHC to infer that the type of @f@ is
actually ’ * - > * ’ .
Let 's try another example :
Although @f@ is on its own here in the class definition, if we take a closer
look at the signature for @fmap@ we can see that @f@ never appears on its
own, but it sits right in front of another type variable every time it shows
up: @f a@ and @f b@.
This information alone is enough for GHC to infer that the type of @f@ is
actually ’* -> *’.
Let's try another example:
-}
class Stuff a where
thing :: a b c d
Here , we can see @a@ has 3 more type variables right after it : @b@ , @c@ and @d@.
This means that @a@ will be given a kind of ’ * - > * - > * - > * ’ .
Another way to let GHC know this is by explicitly providing it with a kind
signature in the class definition itself .
This is exactly what the KindSignatures extension allows us to do :
Here, we can see @a@ has 3 more type variables right after it: @b@, @c@ and @d@.
This means that @a@ will be given a kind of ’* -> * -> * -> *’.
Another way to let GHC know this is by explicitly providing it with a kind
signature in the class definition itself.
This is exactly what the KindSignatures extension allows us to do:
-}
class OfKindTypeToType (a :: Type -> Type)
{-
Here, we've said that the /kind/ of the argument to this class must be a
'Type -> Type' argument. Of course, we actually know plenty of things with
kind 'Type -> Type', even if we haven't thought about it before:
-}
instance OfKindTypeToType Maybe
instance OfKindTypeToType []
instance OfKindTypeToType (Either e) -- What is the kind of 'Either'?
instance OfKindTypeToType ((,) a)
instance OfKindTypeToType IO
Try deleting the kind signature from the ' OfKindTypeToType ' class , and see
that we end up with kind errors for every instance above . We 'll see later on
when we discuss ConstraintKinds and DataKinds that this is one of the
extensions we 'll turn on /every time/ we want to do something a little
complex . I also think it 's a nice one simply for the sake of documentation :
Try deleting the kind signature from the 'OfKindTypeToType' class, and see
that we end up with kind errors for every instance above. We'll see later on
when we discuss ConstraintKinds and DataKinds that this is one of the
extensions we'll turn on /every time/ we want to do something a little
complex. I also think it's a nice one simply for the sake of documentation:
-}
class MyFavouriteBifunctor (element :: (Type -> Type -> Type))
instance MyFavouriteBifunctor Either
instance MyFavouriteBifunctor (,)
So , right now , we can think of all our kinds as being ' Type ' or @a - > b@ for
some kinds @a@ and , and that 's it . However , there 's one more that is
worth mentioning : ' Constraint ' . This is the kind of constraints :
So, right now, we can think of all our kinds as being 'Type' or @a -> b@ for
some kinds @a@ and @b@, and that's it. However, there's one more that is
worth mentioning: 'Constraint'. This is the kind of constraints:
-}
class Whoa (constraint :: Constraint) -- Also from Data.Kind
instance Whoa (Eq Int)
instance Whoa (Show String)
instance Whoa ()
That last one might look a bit odd - is n't ' ( ) ' a type ? Should n't GHC
complain that ' Type ' and ' Constraint ' are different kinds ? Well , in true
fashion , ' ( ) ' is actually overloaded : in the ' Constraint ' kind , it
refers to the " empty constraint " - a constraint that is always true . The
tuple syntax is n't actually that unusual when we think about it :
@
f : : ( Show a , Eq a ) = > a - > a - > String
@
' Constraint ' is the kind of every member on the left side of the fat arrow .
Sometimes , we just have a single constraint . Sometimes , we have several . In
order to have several , we use the tuple syntax . In case you 're interested :
@
g : : ( ) = > a - > a
g = i d
@
This constraint is always satisfied , so it 's not something we see a lot until
we get to constraint programming ( which we 'll cover when we get to
TypeFamilies and ConstraintKinds ) .
That last one might look a bit odd - isn't '()' a type? Shouldn't GHC
complain that 'Type' and 'Constraint' are different kinds? Well, in true
Haskell fashion, '()' is actually overloaded: in the 'Constraint' kind, it
refers to the "empty constraint" - a constraint that is always true. The
tuple syntax isn't actually that unusual when we think about it:
@
f :: (Show a, Eq a) => a -> a -> String
@
'Constraint' is the kind of every member on the left side of the fat arrow.
Sometimes, we just have a single constraint. Sometimes, we have several. In
order to have several, we use the tuple syntax. In case you're interested:
@
g :: () => a -> a
g = id
@
This constraint is always satisfied, so it's not something we see a lot until
we get to constraint programming (which we'll cover when we get to
TypeFamilies and ConstraintKinds).
-}
| null | https://raw.githubusercontent.com/i-am-tom/haskell-exercises/bdf8160fb7a09d577e1871ae29124b2041b3c079/03-KindSignatures/src/KindSignatures.hs | haskell | # LANGUAGE KindSignatures #
we need them, and where they're
just good documentation..
-
Type = (*)
This is a good habit to adopt, as '*' is going to be deprecated soon, in
favour of the more explicit and (hopefully) clear 'Type'. Now, we know all
sorts of things of kind 'Type':
Which extension did we need
to get /these/ to compile?
Here, we've said that the /kind/ of the argument to this class must be a
'Type -> Type' argument. Of course, we actually know plenty of things with
kind 'Type -> Type', even if we haven't thought about it before:
What is the kind of 'Either'?
Also from Data.Kind | # LANGUAGE FlexibleInstances #
3 , in which our heroes discover
We are , hopefully , familiar with the notion of /types/ : @3@ is a value of
type @Int@ , @Nothing@ is a value of @Maybe ( IO String)@ , and so on . However ,
there is also a notion of types /for types/ : kinds .
In our standard , everyday usage , all the types we use have the same kind :
' * ' , which we 'll pronounce ' Type ' . In fact , we can use ' Type ' instead of ' * '
by using the following import .
We are, hopefully, familiar with the notion of /types/: @3@ is a value of
type @Int@, @Nothing@ is a value of @Maybe (IO String)@, and so on. However,
there is also a notion of types /for types/: kinds.
In our standard, everyday usage, all the types we use have the same kind:
'*', which we'll pronounce 'Type'. In fact, we can use 'Type' instead of '*'
by using the following import.
-}
class OfKindType a
instance OfKindType Bool
We can start with an intuition that the ' Type ' kind is inhabited by /things
with a runtime value/. This is n't 100 % accurate , but gives us somewhere to
start : all our /values/ have a type that has a kind of ' Type ' . We can see ,
for example , that @Maybe Int@ is of kind ' Type ' . ' Maybe ' is a funny one ,
though , right ? We could think of it as a " type - level function " :
@
Maybe : : Type - > Type
@
In other words , ' Maybe ' on its own is n't a type - it 's a type /constructor/.
" A ' Maybe ' of ? " , the type - checker asks . ' Maybe Int ' is a type , and
' Maybe ( ) ' is a type , but ' Maybe ' is n't . We can say that ' Maybe ' has kind
' Type - > Type ' because it 's like a function that , given a type , gives us a
type . For example , given ' Int ' , we get ' Maybe Int ' . Given ' ' , we get
' Maybe ' , and so on .
It is because of this that we ca n't write the following instance :
We can start with an intuition that the 'Type' kind is inhabited by /things
with a runtime value/. This isn't 100% accurate, but gives us somewhere to
start: all our /values/ have a type that has a kind of 'Type'. We can see,
for example, that @Maybe Int@ is of kind 'Type'. 'Maybe' is a funny one,
though, right? We could think of it as a "type-level function":
@
Maybe :: Type -> Type
@
In other words, 'Maybe' on its own isn't a type - it's a type /constructor/.
"A 'Maybe' of /what/?", the type-checker asks. 'Maybe Int' is a type, and
'Maybe ()' is a type, but 'Maybe' isn't. We can say that 'Maybe' has kind
'Type -> Type' because it's like a function that, given a type, gives us a
type. For example, given 'Int', we get 'Maybe Int'. Given 'Bool', we get
'Maybe Bool', and so on.
It is because of this that we can't write the following instance:
-}
instance OfKindType Maybe
• Expecting one more argument to ‘ Maybe ’
Expected a type , but ‘ Maybe ’ has kind ‘ * - > * ’
• In the first argument of ‘ OfKindType ’ , namely ‘ Maybe ’
In the instance declaration for ‘ OfKindType Maybe ’
The big problem here is that , in the absence of a better idea , GHC will
assume that a typeclass parameter is of kind ' Type ' .
How do we tell it otherwise ?
One way is to give GHC more information about our type by filling in method
signatures for our class .
For example , let 's take a look at a simplfied definition for the Functor class :
• Expecting one more argument to ‘Maybe’
Expected a type, but ‘Maybe’ has kind ‘* -> *’
• In the first argument of ‘OfKindType’, namely ‘Maybe’
In the instance declaration for ‘OfKindType Maybe’
The big problem here is that, in the absence of a better idea, GHC will
assume that a typeclass parameter is of kind 'Type'.
How do we tell it otherwise?
One way is to give GHC more information about our type by filling in method
signatures for our class.
For example, let's take a look at a simplfied definition for the Functor class:
-}
class Functor f where
fmap :: (a -> b) -> f a -> f b
Although @f@ is on its own here in the class definition , if we take a closer
look at the signature for @fmap@ we can see that never appears on its
own , but it sits right in front of another type variable every time it shows
up : @f a@ and
This information alone is enough for GHC to infer that the type of @f@ is
actually ’ * - > * ’ .
Let 's try another example :
Although @f@ is on its own here in the class definition, if we take a closer
look at the signature for @fmap@ we can see that @f@ never appears on its
own, but it sits right in front of another type variable every time it shows
up: @f a@ and @f b@.
This information alone is enough for GHC to infer that the type of @f@ is
actually ’* -> *’.
Let's try another example:
-}
class Stuff a where
thing :: a b c d
Here , we can see @a@ has 3 more type variables right after it : @b@ , @c@ and @d@.
This means that @a@ will be given a kind of ’ * - > * - > * - > * ’ .
Another way to let GHC know this is by explicitly providing it with a kind
signature in the class definition itself .
This is exactly what the KindSignatures extension allows us to do :
Here, we can see @a@ has 3 more type variables right after it: @b@, @c@ and @d@.
This means that @a@ will be given a kind of ’* -> * -> * -> *’.
Another way to let GHC know this is by explicitly providing it with a kind
signature in the class definition itself.
This is exactly what the KindSignatures extension allows us to do:
-}
class OfKindTypeToType (a :: Type -> Type)
instance OfKindTypeToType Maybe
instance OfKindTypeToType []
instance OfKindTypeToType ((,) a)
instance OfKindTypeToType IO
Try deleting the kind signature from the ' OfKindTypeToType ' class , and see
that we end up with kind errors for every instance above . We 'll see later on
when we discuss ConstraintKinds and DataKinds that this is one of the
extensions we 'll turn on /every time/ we want to do something a little
complex . I also think it 's a nice one simply for the sake of documentation :
Try deleting the kind signature from the 'OfKindTypeToType' class, and see
that we end up with kind errors for every instance above. We'll see later on
when we discuss ConstraintKinds and DataKinds that this is one of the
extensions we'll turn on /every time/ we want to do something a little
complex. I also think it's a nice one simply for the sake of documentation:
-}
class MyFavouriteBifunctor (element :: (Type -> Type -> Type))
instance MyFavouriteBifunctor Either
instance MyFavouriteBifunctor (,)
So , right now , we can think of all our kinds as being ' Type ' or @a - > b@ for
some kinds @a@ and , and that 's it . However , there 's one more that is
worth mentioning : ' Constraint ' . This is the kind of constraints :
So, right now, we can think of all our kinds as being 'Type' or @a -> b@ for
some kinds @a@ and @b@, and that's it. However, there's one more that is
worth mentioning: 'Constraint'. This is the kind of constraints:
-}
instance Whoa (Eq Int)
instance Whoa (Show String)
instance Whoa ()
That last one might look a bit odd - is n't ' ( ) ' a type ? Should n't GHC
complain that ' Type ' and ' Constraint ' are different kinds ? Well , in true
fashion , ' ( ) ' is actually overloaded : in the ' Constraint ' kind , it
refers to the " empty constraint " - a constraint that is always true . The
tuple syntax is n't actually that unusual when we think about it :
@
f : : ( Show a , Eq a ) = > a - > a - > String
@
' Constraint ' is the kind of every member on the left side of the fat arrow .
Sometimes , we just have a single constraint . Sometimes , we have several . In
order to have several , we use the tuple syntax . In case you 're interested :
@
g : : ( ) = > a - > a
g = i d
@
This constraint is always satisfied , so it 's not something we see a lot until
we get to constraint programming ( which we 'll cover when we get to
TypeFamilies and ConstraintKinds ) .
That last one might look a bit odd - isn't '()' a type? Shouldn't GHC
complain that 'Type' and 'Constraint' are different kinds? Well, in true
Haskell fashion, '()' is actually overloaded: in the 'Constraint' kind, it
refers to the "empty constraint" - a constraint that is always true. The
tuple syntax isn't actually that unusual when we think about it:
@
f :: (Show a, Eq a) => a -> a -> String
@
'Constraint' is the kind of every member on the left side of the fat arrow.
Sometimes, we just have a single constraint. Sometimes, we have several. In
order to have several, we use the tuple syntax. In case you're interested:
@
g :: () => a -> a
g = id
@
This constraint is always satisfied, so it's not something we see a lot until
we get to constraint programming (which we'll cover when we get to
TypeFamilies and ConstraintKinds).
-}
|
fe8b98bea1d68642c9a58d782cfb06ccf899688360508367b82d9f48572cb1f9 | mojombo/ernie | ernie_config.erl | -module(ernie_config).
-export([load/1]).
load(ConfigFile) ->
{ok, Configs} = file:consult(ConfigFile),
Configs2 = lists:map((fun load_single/1), Configs),
{ok, Configs2}.
load_single(Config) ->
case proplists:get_value(type, Config) of
native ->
verify(native, Config),
CodePaths = proplists:get_value(codepaths, Config),
lists:map((fun code:add_patha/1), CodePaths),
Mod = proplists:get_value(module, Config),
code:load_file(Mod),
[{id, native} | Config];
external ->
verify(external, Config),
Handler = proplists:get_value(command, Config),
Number = proplists:get_value(count, Config),
{ok, SupPid} = asset_pool_sup:start_link(Handler, Number),
[{_Id, ChildPid, _Type, _Modules}] = supervisor:which_children(SupPid),
[{id, ChildPid} | Config]
end.
verify(native, _Config) ->
ok;
verify(external, _Config) ->
ok. | null | https://raw.githubusercontent.com/mojombo/ernie/a21664e668038291bdbe42684d46cb112242aa7b/elib/ernie_config.erl | erlang | -module(ernie_config).
-export([load/1]).
load(ConfigFile) ->
{ok, Configs} = file:consult(ConfigFile),
Configs2 = lists:map((fun load_single/1), Configs),
{ok, Configs2}.
load_single(Config) ->
case proplists:get_value(type, Config) of
native ->
verify(native, Config),
CodePaths = proplists:get_value(codepaths, Config),
lists:map((fun code:add_patha/1), CodePaths),
Mod = proplists:get_value(module, Config),
code:load_file(Mod),
[{id, native} | Config];
external ->
verify(external, Config),
Handler = proplists:get_value(command, Config),
Number = proplists:get_value(count, Config),
{ok, SupPid} = asset_pool_sup:start_link(Handler, Number),
[{_Id, ChildPid, _Type, _Modules}] = supervisor:which_children(SupPid),
[{id, ChildPid} | Config]
end.
verify(native, _Config) ->
ok;
verify(external, _Config) ->
ok. | |
6b705daa4cb08dec06f406a9e661ed078970eb9d76f5edad68e5a2ad9b07080c | haskell-suite/haskell-src-exts | TySplice4.hs | # LANGUAGE TemplateHaskell #
x = [d| f :: a -> Int
f x = 1 |]
y = [d| f2 :: a -> Int; f2 x = 1 |]
| null | https://raw.githubusercontent.com/haskell-suite/haskell-src-exts/84a4930e0e5c051b7d9efd20ef7c822d5fc1c33b/tests/examples/TySplice4.hs | haskell | # LANGUAGE TemplateHaskell #
x = [d| f :: a -> Int
f x = 1 |]
y = [d| f2 :: a -> Int; f2 x = 1 |]
| |
c48d21e5e8260fe52311170574727676742c59aa928072a328cb8df0c202e802 | Kappa-Dev/KappaTools | common_args.mli | (******************************************************************************)
(* _ __ * The Kappa Language *)
| |/ / * Copyright 2010 - 2020 CNRS - Harvard Medical School - INRIA - IRIF
(* | ' / *********************************************************************)
(* | . \ * This file is distributed under the terms of the *)
(* |_|\_\ * GNU Lesser General Public License Version 3 *)
(******************************************************************************)
val data_set: Superarg.category
val output: Superarg.category
val semantics: Superarg.category
val integration_settings: Superarg.category
val model_reduction: Superarg.category
val static_analysis: Superarg.category
val debug_mode: Superarg.category
type t = {
mutable backtrace : bool;
mutable debug : bool;
}
type t_gui
val default : t
val default_gui : t_gui
(* return options *)
val options : t -> (string * Arg.spec * string) list
val options_gui :
t_gui ->
(string * Superarg.spec * string * (Superarg.category * Superarg.position) list * Superarg.level) list
val copy_from_gui: t_gui -> t -> unit
| null | https://raw.githubusercontent.com/Kappa-Dev/KappaTools/eef2337e8688018eda47ccc838aea809cae68de7/core/cli/common_args.mli | ocaml | ****************************************************************************
_ __ * The Kappa Language
| ' / ********************************************************************
| . \ * This file is distributed under the terms of the
|_|\_\ * GNU Lesser General Public License Version 3
****************************************************************************
return options | | |/ / * Copyright 2010 - 2020 CNRS - Harvard Medical School - INRIA - IRIF
val data_set: Superarg.category
val output: Superarg.category
val semantics: Superarg.category
val integration_settings: Superarg.category
val model_reduction: Superarg.category
val static_analysis: Superarg.category
val debug_mode: Superarg.category
type t = {
mutable backtrace : bool;
mutable debug : bool;
}
type t_gui
val default : t
val default_gui : t_gui
val options : t -> (string * Arg.spec * string) list
val options_gui :
t_gui ->
(string * Superarg.spec * string * (Superarg.category * Superarg.position) list * Superarg.level) list
val copy_from_gui: t_gui -> t -> unit
|
d691b40b3e4e42530defe4f9a93aef874fd4e91132b4dbdc9cc5be57f7e6ffca | solita/mnt-teet | enum_values.clj | (ns teet.migration.enum-values
(:require [datomic.client.api :as d]))
(defn remove-old-task-types [conn]
(let [types (d/q '[:find (pull ?e [*])
:where [?e :enum/attribute :task/type]]
(d/db conn))]
(d/transact
conn
{:tx-data (for [[{id :db/id}] types]
[:db/retractEntity id])})))
| null | https://raw.githubusercontent.com/solita/mnt-teet/7a5124975ce1c7f3e7a7c55fe23257ca3f7b6411/app/backend/src/clj/teet/migration/enum_values.clj | clojure | (ns teet.migration.enum-values
(:require [datomic.client.api :as d]))
(defn remove-old-task-types [conn]
(let [types (d/q '[:find (pull ?e [*])
:where [?e :enum/attribute :task/type]]
(d/db conn))]
(d/transact
conn
{:tx-data (for [[{id :db/id}] types]
[:db/retractEntity id])})))
| |
c9d1c15cfb850a81ed9a69f368fdba7a5b72c88e293923ab0027764edd37dfaa | ppaml-op3/insomnia | Racket.hs | -- | AST for a fragment of Racket. At this level of detail we don't
-- worry about certain forms being macros.
# LANGUAGE DeriveDataTypeable , DeriveGeneric #
module Gambling.Racket where
import Data.Typeable (Typeable)
import GHC.Generics (Generic)
import Unbound.Generics.LocallyNameless
import Insomnia.Common.Literal
type Var = Name Expr
-- term
data Expr =
Var Var
| StringLit String
| QuoteSymbol String
| Literal Literal
| App [Expr]
| Lam (Bind [Var] Body)
| Let (Bind Bindings Body)
| LetRec (Bind (Rec Bindings) Body)
| Match Expr [Clause]
deriving (Show, Generic, Typeable)
-- pattern
type Bindings = [Binding]
-- pattern
data Binding = Binding Var (Embed Expr)
deriving (Show, Generic, Typeable)
-- term
newtype Clause =
Clause (Bind Pattern Body)
deriving (Show, Generic, Typeable)
-- pattern
data Pattern =
VarP Var
| WildP
| ConsP Pattern Pattern
| QuoteSymbolP (Embed String)
deriving (Show, Generic, Typeable)
-- term
--
-- Racket calls these "internal definition contexts" and uses the
-- metavar /body/
newtype Body = Body (Bind (Rec [InternalDefn]) Expr)
deriving (Show, Generic, Typeable)
-- pattern
data InternalDefn =
DefnID Definition
| ExprID (Embed Expr) -- no definition, just a bare expression
deriving (Show, Generic, Typeable)
-- pattern
data Definition = Define (Rebind Var (Embed Expr))
deriving (Show, Generic, Typeable)
type ModuleIdentifier = Var
type ModuleLanguage = String
-- term
data Module = Module {
_moduleId :: ModuleIdentifier
, _moduleLanguage :: ModuleLanguage
, _moduleBody :: ModuleDefnCtx
}
deriving (Show, Generic, Typeable)
-- term
newtype ModuleDefnCtx =
ModuleDefnCtx (Bind (Rec [ModuleBinding]) Provides)
deriving (Show, Generic, Typeable)
type ModulePath = String
-- pattern
data ModuleBinding =
DefnMB Definition
| ExprMB (Embed Expr)
| RequireMB Requires
deriving (Show, Generic, Typeable)
data RequirePath =
RequireFilePath FilePath
| RequireModulePath ModulePath
deriving (Show, Generic, Typeable)
-- pattern
data Requires = Requires (Embed RequirePath) [Var]
| RequiresAll (Embed RequirePath)
deriving (Show, Generic, Typeable)
-- term
data Provides = Provides [Var]
| ProvidesAll
deriving (Show, Generic, Typeable)
instance Alpha Expr
instance Alpha Body
instance Alpha Binding
instance Alpha Clause
instance Alpha Pattern
instance Alpha InternalDefn
instance Alpha Definition
instance Alpha Provides
instance Alpha RequirePath
instance Alpha Requires
instance Alpha ModuleBinding
instance Alpha ModuleDefnCtx
instance Alpha Module
| null | https://raw.githubusercontent.com/ppaml-op3/insomnia/5fc6eb1d554e8853d2fc929a957c7edce9e8867d/src/Gambling/Racket.hs | haskell | | AST for a fragment of Racket. At this level of detail we don't
worry about certain forms being macros.
term
pattern
pattern
term
pattern
term
Racket calls these "internal definition contexts" and uses the
metavar /body/
pattern
no definition, just a bare expression
pattern
term
term
pattern
pattern
term | # LANGUAGE DeriveDataTypeable , DeriveGeneric #
module Gambling.Racket where
import Data.Typeable (Typeable)
import GHC.Generics (Generic)
import Unbound.Generics.LocallyNameless
import Insomnia.Common.Literal
type Var = Name Expr
data Expr =
Var Var
| StringLit String
| QuoteSymbol String
| Literal Literal
| App [Expr]
| Lam (Bind [Var] Body)
| Let (Bind Bindings Body)
| LetRec (Bind (Rec Bindings) Body)
| Match Expr [Clause]
deriving (Show, Generic, Typeable)
type Bindings = [Binding]
data Binding = Binding Var (Embed Expr)
deriving (Show, Generic, Typeable)
newtype Clause =
Clause (Bind Pattern Body)
deriving (Show, Generic, Typeable)
data Pattern =
VarP Var
| WildP
| ConsP Pattern Pattern
| QuoteSymbolP (Embed String)
deriving (Show, Generic, Typeable)
newtype Body = Body (Bind (Rec [InternalDefn]) Expr)
deriving (Show, Generic, Typeable)
data InternalDefn =
DefnID Definition
deriving (Show, Generic, Typeable)
data Definition = Define (Rebind Var (Embed Expr))
deriving (Show, Generic, Typeable)
type ModuleIdentifier = Var
type ModuleLanguage = String
data Module = Module {
_moduleId :: ModuleIdentifier
, _moduleLanguage :: ModuleLanguage
, _moduleBody :: ModuleDefnCtx
}
deriving (Show, Generic, Typeable)
newtype ModuleDefnCtx =
ModuleDefnCtx (Bind (Rec [ModuleBinding]) Provides)
deriving (Show, Generic, Typeable)
type ModulePath = String
data ModuleBinding =
DefnMB Definition
| ExprMB (Embed Expr)
| RequireMB Requires
deriving (Show, Generic, Typeable)
data RequirePath =
RequireFilePath FilePath
| RequireModulePath ModulePath
deriving (Show, Generic, Typeable)
data Requires = Requires (Embed RequirePath) [Var]
| RequiresAll (Embed RequirePath)
deriving (Show, Generic, Typeable)
data Provides = Provides [Var]
| ProvidesAll
deriving (Show, Generic, Typeable)
instance Alpha Expr
instance Alpha Body
instance Alpha Binding
instance Alpha Clause
instance Alpha Pattern
instance Alpha InternalDefn
instance Alpha Definition
instance Alpha Provides
instance Alpha RequirePath
instance Alpha Requires
instance Alpha ModuleBinding
instance Alpha ModuleDefnCtx
instance Alpha Module
|
93bf393968326b6c6f36374fbfd8936dc1d4d965be3758f1ddbb1fe846c6ca5e | yzh44yzh/practical_erlang | ping_handler.erl | -module(ping_handler).
-behaviour(cowboy_handler).
-export([init/2]).
init(Req0, State) ->
Headers = #{
<<"content-type">> => <<"text/html">>
},
Body = <<
"<h1>Hello from Cowboy</h1>"
"<p>This is ping_handler</p>"
>>,
Req1 = cowboy_req:reply(200, Headers, Body, Req0),
{ok, Req1, State}. | null | https://raw.githubusercontent.com/yzh44yzh/practical_erlang/c9eec8cf44e152bf50d9bc6d5cb87fee4764f609/17_web_server/ws/apps/ws/src/handlers/ping_handler.erl | erlang | -module(ping_handler).
-behaviour(cowboy_handler).
-export([init/2]).
init(Req0, State) ->
Headers = #{
<<"content-type">> => <<"text/html">>
},
Body = <<
"<h1>Hello from Cowboy</h1>"
"<p>This is ping_handler</p>"
>>,
Req1 = cowboy_req:reply(200, Headers, Body, Req0),
{ok, Req1, State}. | |
f63df39592e8e919ee9a753d00696b76cbf18120693f4078cbd82db88b621977 | project-oak/hafnium-verification | Language.mli |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
type t = Clang | Java [@@deriving compare]
val equal : t -> t -> bool
val to_string : t -> string
val to_explicit_string : t -> string
val of_string : string -> t option
val curr_language : t ref
val curr_language_is : t -> bool
| null | https://raw.githubusercontent.com/project-oak/hafnium-verification/6071eff162148e4d25a0fedaea003addac242ace/experiments/ownership-inference/infer/infer/src/base/Language.mli | ocaml |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
type t = Clang | Java [@@deriving compare]
val equal : t -> t -> bool
val to_string : t -> string
val to_explicit_string : t -> string
val of_string : string -> t option
val curr_language : t ref
val curr_language_is : t -> bool
| |
24aec84659c15bf564bbbe27181a23d1266dc6fc0363ac06321cf3a7a13d5504 | Swirrl/cubiql | dataset.clj | (ns cubiql.schema.mapping.dataset
(:require [cubiql.util :as util]
[cubiql.vocabulary :refer [qb:measureType]]))
(def uri :uri)
(def schema :schema)
(def dimensions :dimensions)
(def measures :measures)
(defn description [dataset-mapping]
;;TODO: add dataset description to mapping!
"")
(defn components [dataset-mapping]
(concat (dimensions dataset-mapping) (measures dataset-mapping)))
(defn numeric-measure-mappings [dataset-mapping]
(seq (filter :is-numeric? (measures dataset-mapping))))
(defn- find-by-uri [components uri]
(util/find-first (fn [comp] (= uri (:uri comp))) components))
(defn get-component-by-uri [dataset-mapping uri]
(find-by-uri (components dataset-mapping) uri))
(defn get-dimension-by-uri [dataset-mapping uri]
(find-by-uri (dimensions dataset-mapping) uri))
(defn get-measure-by-uri [dataset-mapping uri]
(find-by-uri (measures dataset-mapping) uri))
(defn- find-by-enum-name [components enum-name]
(util/find-first (fn [comp] (= enum-name (:enum-name comp))) components))
(defn get-component-by-enum-name [dataset-mapping enum-name]
(find-by-enum-name (components dataset-mapping) enum-name))
(defn- find-by-field-name [components field-name]
(util/find-first (fn [comp] (= field-name (:field-name comp))) components))
(defn get-component-by-field-name [dataset-mapping field-name]
(find-by-field-name (components dataset-mapping) field-name))
(defn get-dimension-by-field-name [dataset-mapping field-name]
(find-by-field-name (dimensions dataset-mapping) field-name))
(defn component-mapping->component [comp]
(or (:dimension comp) (:measure comp)))
(defn components-enum-group [dataset-mapping]
(:components-enum dataset-mapping))
(defn aggregation-measures-enum-group [dataset-mapping]
(:aggregation-measures-enum dataset-mapping))
(defn has-measure-type-dimension?
"Whether the given dataset has an explicit qb:measureType dimension"
[dataset-mapping]
(let [dims (dimensions dataset-mapping)
measure-dim (some (fn [dim] (= qb:measureType (:uri dim))) dims)]
(some? measure-dim))) | null | https://raw.githubusercontent.com/Swirrl/cubiql/67efdc51750b9ac4fd1cdfbcddfb80398189807f/src/cubiql/schema/mapping/dataset.clj | clojure | TODO: add dataset description to mapping! | (ns cubiql.schema.mapping.dataset
(:require [cubiql.util :as util]
[cubiql.vocabulary :refer [qb:measureType]]))
(def uri :uri)
(def schema :schema)
(def dimensions :dimensions)
(def measures :measures)
(defn description [dataset-mapping]
"")
(defn components [dataset-mapping]
(concat (dimensions dataset-mapping) (measures dataset-mapping)))
(defn numeric-measure-mappings [dataset-mapping]
(seq (filter :is-numeric? (measures dataset-mapping))))
(defn- find-by-uri [components uri]
(util/find-first (fn [comp] (= uri (:uri comp))) components))
(defn get-component-by-uri [dataset-mapping uri]
(find-by-uri (components dataset-mapping) uri))
(defn get-dimension-by-uri [dataset-mapping uri]
(find-by-uri (dimensions dataset-mapping) uri))
(defn get-measure-by-uri [dataset-mapping uri]
(find-by-uri (measures dataset-mapping) uri))
(defn- find-by-enum-name [components enum-name]
(util/find-first (fn [comp] (= enum-name (:enum-name comp))) components))
(defn get-component-by-enum-name [dataset-mapping enum-name]
(find-by-enum-name (components dataset-mapping) enum-name))
(defn- find-by-field-name [components field-name]
(util/find-first (fn [comp] (= field-name (:field-name comp))) components))
(defn get-component-by-field-name [dataset-mapping field-name]
(find-by-field-name (components dataset-mapping) field-name))
(defn get-dimension-by-field-name [dataset-mapping field-name]
(find-by-field-name (dimensions dataset-mapping) field-name))
(defn component-mapping->component [comp]
(or (:dimension comp) (:measure comp)))
(defn components-enum-group [dataset-mapping]
(:components-enum dataset-mapping))
(defn aggregation-measures-enum-group [dataset-mapping]
(:aggregation-measures-enum dataset-mapping))
(defn has-measure-type-dimension?
"Whether the given dataset has an explicit qb:measureType dimension"
[dataset-mapping]
(let [dims (dimensions dataset-mapping)
measure-dim (some (fn [dim] (= qb:measureType (:uri dim))) dims)]
(some? measure-dim))) |
dd120988fecb0fdc12e9370619cec48eef872230a1b6e4e7ca07fdde67d145b7 | Ptival/chick | Chick.hs | module PrettyPrinting.Chick () where
import PrettyPrinting.Chick.Binder ()
import PrettyPrinting.Chick.Constructor ()
import PrettyPrinting . . Declaration ( )
import PrettyPrinting.Chick.Definition ()
import PrettyPrinting.Chick.DefinitionObjectKind ()
import PrettyPrinting.Chick.GlobalDeclaration ()
import PrettyPrinting.Chick.GlobalEnvironment ()
import PrettyPrinting.Chick.Inductive ()
import PrettyPrinting.Chick.List ()
import PrettyPrinting.Chick.LocalContext ()
import PrettyPrinting.Chick.LocalDeclaration ()
import PrettyPrinting.Chick.Pair ()
import PrettyPrinting.Chick.Script ()
import PrettyPrinting.Chick.Term ()
import PrettyPrinting.Chick.Triple ()
import PrettyPrinting.Chick.Unit ()
import PrettyPrinting.Chick.Variable ()
import PrettyPrinting.Chick.Vernacular ()
| null | https://raw.githubusercontent.com/Ptival/chick/a5ce39a842ff72348f1c9cea303997d5300163e2/backend/lib/PrettyPrinting/Chick.hs | haskell | module PrettyPrinting.Chick () where
import PrettyPrinting.Chick.Binder ()
import PrettyPrinting.Chick.Constructor ()
import PrettyPrinting . . Declaration ( )
import PrettyPrinting.Chick.Definition ()
import PrettyPrinting.Chick.DefinitionObjectKind ()
import PrettyPrinting.Chick.GlobalDeclaration ()
import PrettyPrinting.Chick.GlobalEnvironment ()
import PrettyPrinting.Chick.Inductive ()
import PrettyPrinting.Chick.List ()
import PrettyPrinting.Chick.LocalContext ()
import PrettyPrinting.Chick.LocalDeclaration ()
import PrettyPrinting.Chick.Pair ()
import PrettyPrinting.Chick.Script ()
import PrettyPrinting.Chick.Term ()
import PrettyPrinting.Chick.Triple ()
import PrettyPrinting.Chick.Unit ()
import PrettyPrinting.Chick.Variable ()
import PrettyPrinting.Chick.Vernacular ()
| |
27bce5e2d8966e946050fc7e89454c0a42f857d94090aa44787b89168d27ac51 | dcSpark/fracada | Emulator.hs | {-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DeriveGeneric #
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE NoImplicitPrelude #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE NumericUnderscores #-}
import Prelude (IO, (<>))
import PlutusTx.Prelude hiding (Semigroup(..), unless)
import Ledger.Value as Value
import Plutus.Trace.Emulator as Emulator
import Wallet.Emulator.Wallet
import Fracada
import Ledger.Ada as Ada
import qualified Data.Map as Map
import Control.Monad hiding (fmap)
import Data.Default (Default (..))
nftCurrency :: CurrencySymbol
nftCurrency = "66"
nftName :: TokenName
nftName = "NFT"
nft :: AssetClass
nft = AssetClass (nftCurrency, nftName)
main :: IO ()
main = do
runEmulatorTraceIO' def emCfg scenario1
runEmulatorTraceIO' def emCfg scenario2
emCfg :: EmulatorConfig
emCfg = EmulatorConfig (Left $ Map.fromList [(knownWallet w, v) | w <- [1 .. 2]]) def def
where
v = Ada.lovelaceValueOf 1000_000_000 <> assetClassValue nft 1
scenario1 :: EmulatorTrace ()
scenario1 = do
h1 <- activateContractWallet (knownWallet 1) endpoints
void $ Emulator.waitNSlots 1
let
toFraction = ToFraction
{ nftAsset = nft
, fractions = 10
, fractionTokenName = tokenName "Frac"
}
callEndpoint @"1-fractionNFT" h1 toFraction
void $ Emulator.waitNSlots 1
callEndpoint @"2-returnNFT" h1 nft
void $ Emulator.waitNSlots 1
scenario2 :: EmulatorTrace ()
scenario2 = do
h1 <- activateContractWallet (knownWallet 1) endpoints
h2 <- activateContractWallet (knownWallet 2) endpoints
void $ Emulator.waitNSlots 1
let
toFraction = ToFraction
{ nftAsset = nft
, fractions = 10
, fractionTokenName = tokenName "Frac"
}
callEndpoint @"1 - lockNFT " h1 nft
callEndpoint @"1-fractionNFT" h1 toFraction
void $ Emulator.waitNSlots 1
callEndpoint @"2-returnNFT" h2 nft
void $ Emulator.waitNSlots 1 | null | https://raw.githubusercontent.com/dcSpark/fracada/8da585575313b1c8e4fc8d30dcaf21d11ad6197c/exe/Emulator.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE DeriveAnyClass #
# LANGUAGE FlexibleContexts #
# LANGUAGE OverloadedStrings #
# LANGUAGE TypeOperators #
# LANGUAGE NumericUnderscores # | # LANGUAGE DeriveGeneric #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
import Prelude (IO, (<>))
import PlutusTx.Prelude hiding (Semigroup(..), unless)
import Ledger.Value as Value
import Plutus.Trace.Emulator as Emulator
import Wallet.Emulator.Wallet
import Fracada
import Ledger.Ada as Ada
import qualified Data.Map as Map
import Control.Monad hiding (fmap)
import Data.Default (Default (..))
nftCurrency :: CurrencySymbol
nftCurrency = "66"
nftName :: TokenName
nftName = "NFT"
nft :: AssetClass
nft = AssetClass (nftCurrency, nftName)
main :: IO ()
main = do
runEmulatorTraceIO' def emCfg scenario1
runEmulatorTraceIO' def emCfg scenario2
emCfg :: EmulatorConfig
emCfg = EmulatorConfig (Left $ Map.fromList [(knownWallet w, v) | w <- [1 .. 2]]) def def
where
v = Ada.lovelaceValueOf 1000_000_000 <> assetClassValue nft 1
scenario1 :: EmulatorTrace ()
scenario1 = do
h1 <- activateContractWallet (knownWallet 1) endpoints
void $ Emulator.waitNSlots 1
let
toFraction = ToFraction
{ nftAsset = nft
, fractions = 10
, fractionTokenName = tokenName "Frac"
}
callEndpoint @"1-fractionNFT" h1 toFraction
void $ Emulator.waitNSlots 1
callEndpoint @"2-returnNFT" h1 nft
void $ Emulator.waitNSlots 1
scenario2 :: EmulatorTrace ()
scenario2 = do
h1 <- activateContractWallet (knownWallet 1) endpoints
h2 <- activateContractWallet (knownWallet 2) endpoints
void $ Emulator.waitNSlots 1
let
toFraction = ToFraction
{ nftAsset = nft
, fractions = 10
, fractionTokenName = tokenName "Frac"
}
callEndpoint @"1 - lockNFT " h1 nft
callEndpoint @"1-fractionNFT" h1 toFraction
void $ Emulator.waitNSlots 1
callEndpoint @"2-returnNFT" h2 nft
void $ Emulator.waitNSlots 1 |
f7ee6ffb74bb24ade41b296d2de5f64e30e4db44b420e8001ee5a16b1f93bea2 | stumpwm/stumpwm-contrib | package.lisp | package.lisp
(defpackage #:swm-emacs
(:use #:cl :stumpwm))
| null | https://raw.githubusercontent.com/stumpwm/stumpwm-contrib/a7dc1c663d04e6c73a4772c8a6ad56a34381096a/util/swm-emacs/package.lisp | lisp | package.lisp
(defpackage #:swm-emacs
(:use #:cl :stumpwm))
| |
ef898fb96fb9773f28aa3f305d408da98bcab69ebcde457a84c77e6fd7c3ac77 | nanocaml/nanocaml | pass_typeck_tests.ml | open OUnit2
open Migrate_parsetree
open Ast_405.Parsetree
open Ast_405.Ast_helper
let test_L0 = Parsing_tests.test_L0
let test_L0_a = Parsing_tests.test_L0_a
let tt =
"pass_typeck" >:::
let open Nanocaml.Pass in
let open Nanocaml.Lang in
let module TC = Nanocaml.Pass_typeck in
let loc = !default_loc in
let pass1 =
[%stri let[@pass Test_L0 => Test_L0] pass1 =
let rec a = function
| `A _ -> true
| `A0 -> false
and b = function
| `B x -> a x
in
a]
|> Parsing_tests.stri_value_binding
|> pass_of_value_binding
in
let any = NPpat_any loc in
let var_x = NPpat_var {txt = "x"; loc} in
[
"catamorphism(1)" >::
begin fun _ ->
let pass =
Parsing_tests.stri_value_binding
[%stri let[@pass Test_L0 => Test_L0] s =
let rec a = function
| `A0 _ -> 0
in 0 ]
|> pass_of_value_binding
in
match TC.catamorphism ~loc ~pass test_L0_a with
| {pexp_desc = Pexp_ident {txt = Lident "a"}} -> ()
| _ -> assert_failure "cata of 'a' has wrong form"
end;
"catamorphism(2)" >::
begin fun _ ->
let pass =
Parsing_tests.stri_value_binding
[%stri let[@pass Test_L0 => Test_L0] s =
let rec b = function
| `B _ -> 0
in 0 ]
|> pass_of_value_binding;
in
try
TC.catamorphism ~loc ~pass test_L0_a
|> ignore;
assert_failure "expected cata for 'a' to fail (not defined)"
with Location.Error _ -> ()
end;
"typeck_pat(1)" >::
begin fun _ ->
assert_equal any (TC.typeck_pat ~pass:pass1 (NP_nonterm "a") any);
assert_equal var_x (TC.typeck_pat ~pass:pass1 (NP_nonterm "b") var_x);
end;
"typeck_pat(2)" >::
begin fun _ ->
let pat = NPpat_variant ("A", Some any, loc) in
assert_equal pat (TC.typeck_pat ~pass:pass1 (NP_nonterm "a") pat);
end;
"typeck_pat(3)" >::
begin fun _ ->
let pat = NPpat_alias (var_x, {txt = "y"; loc}) in
assert_equal pat (TC.typeck_pat ~pass:pass1 (NP_nonterm "a") pat);
assert_equal pat (TC.typeck_pat ~pass:pass1 (NP_term [%type: int]) pat);
end;
"typeck_pat(4)" >::
begin fun _ ->
let pat = NPpat_tuple ([ any; any ], loc) in
assert_equal pat (TC.typeck_pat ~pass:pass1
(NP_tuple [ NP_term [%type: int]; NP_nonterm "a" ])
pat);
end;
"typeck_pat(5)" >::
begin fun _ ->
try
TC.typeck_pat ~pass:pass1
(NP_tuple [ NP_term [%type: int];
NP_nonterm "a" ])
(NPpat_tuple ([ any; any; any ], loc))
|> ignore;
assert_failure "expected bad arg-count tuple to fail"
with Location.Error e ->
assert_equal "wrong number of tuple arguments; expected 2, found 3" e.msg
~printer:(Printf.sprintf "%S")
end;
"typeck_pat(6)" >::
begin fun _ ->
match (TC.typeck_pat ~pass:pass1
(NP_nonterm "a")
(NPpat_cata (var_x, None))) with
(* x [@r] ==> x [@r a] *)
| NPpat_cata (NPpat_var {txt = "x"},
Some {pexp_desc =
Pexp_ident {txt = Lident "a"}})
-> ()
| _ -> assert_failure "elaborated (x [@r] : a) has wrong form"
end;
"typeck_pat(7)" >::
begin fun _ ->
match (TC.typeck_pat ~pass:pass1
(NP_list (NP_tuple [ NP_nonterm "a";
NP_term [%type: int] ]))
(NPpat_cata (var_x, None))) with
(* x [@r] ==> (_ [@r a], _) [@l] as x *)
| NPpat_alias (NPpat_map (NPpat_tuple
([ NPpat_cata (NPpat_any _, Some _);
NPpat_any _ ],
_)),
{txt = "x"}) -> ()
| _ -> assert_failure "elaborated (x [@r] : (a * int) list) has wrong form"
end;
"typeck_nonterm(1)" >::
begin fun _ ->
assert_equal None (TC.typeck_nonterm ~pass:pass1 ~loc "a" "A0" None);
assert_equal (Some var_x) (TC.typeck_nonterm ~pass:pass1 ~loc "a" "A" (Some var_x));
end;
"typeck_nonterm(2)" >::
begin fun _ ->
try
TC.typeck_nonterm ~pass:pass1 ~loc "a" "A0" (Some any)
|> ignore; assert_failure "expected typeck to fail (nonterm doesn't expect arguments)"
with Location.Error e ->
assert_equal "unexpected" (String.sub e.msg 0 10)
~printer:(Printf.sprintf "%S")
end;
"typeck_nonterm(3)" >::
begin fun _ ->
try
TC.typeck_nonterm ~pass:pass1 ~loc "a" "A" None
|> ignore; assert_failure "expected typeck to fail (nonterm expects arguments)"
with Location.Error e ->
assert_equal "expected" (String.sub e.msg 0 8)
~printer:(Printf.sprintf "%S")
end;
"typeck_cata(1)" >::
begin fun _ ->
let cata = [%expr fn a b c] in
assert_equal (`Infer cata)
(TC.typeck_cata ~pass:pass1 ~loc (Some cata) (NP_nonterm "a") any);
assert_equal (`Infer (Exp.ident ~loc {txt = Lident "a"; loc}))
(TC.typeck_cata ~pass:pass1 ~loc None (NP_nonterm "a") any);
assert_equal (`Rewrite any)
(TC.typeck_cata ~pass:pass1 ~loc None (NP_term [%type: int]) any);
end;
"typeck_cata(2)" >::
begin fun _ ->
match TC.typeck_cata ~pass:pass1 ~loc None
(NP_tuple [ NP_term [%type: int]; NP_nonterm "a" ])
any
with
| `Rewrite (NPpat_tuple ([ NPpat_cata (_, None);
NPpat_cata (_, None) ], _)) -> ()
| _ -> assert_failure "rewritten tuple has wrong form"
end;
"typeck_cata(3)" >::
begin fun _ ->
match TC.typeck_cata ~pass:pass1 ~loc None
(NP_tuple [ NP_term [%type: int]; NP_nonterm "a" ])
var_x
with
| `Rewrite (NPpat_alias
(NPpat_tuple ([ NPpat_cata (_, None);
NPpat_cata (_, None) ], _),
{txt = "x"})) -> ()
| _ -> assert_failure "rewritten tuple (+ alias) has wrong form"
end;
"typeck_cata(4)" >::
begin fun _ ->
let cata = [%expr fn a b c] in
match TC.typeck_cata ~pass:pass1 ~loc (Some cata)
(NP_list (NP_nonterm "a"))
any
with
| `Rewrite (NPpat_map (NPpat_cata (NPpat_any _, Some _))) -> ()
| _ -> assert_failure "rewritten list has wrong form"
end;
"typeck_cata(5)" >::
begin fun _ ->
try
TC.typeck_cata ~pass:pass1 ~loc None
(NP_nonterm "a")
(NPpat_variant ("A", None, loc))
|> ignore;
assert_failure "expected non-total pattern in cata result to fail"
with Location.Error _ -> ()
end;
]
| null | https://raw.githubusercontent.com/nanocaml/nanocaml/c856268dc8986bd9fb739c8cd6b972052997a30c/test/pass_typeck_tests.ml | ocaml | x [@r] ==> x [@r a]
x [@r] ==> (_ [@r a], _) [@l] as x | open OUnit2
open Migrate_parsetree
open Ast_405.Parsetree
open Ast_405.Ast_helper
let test_L0 = Parsing_tests.test_L0
let test_L0_a = Parsing_tests.test_L0_a
let tt =
"pass_typeck" >:::
let open Nanocaml.Pass in
let open Nanocaml.Lang in
let module TC = Nanocaml.Pass_typeck in
let loc = !default_loc in
let pass1 =
[%stri let[@pass Test_L0 => Test_L0] pass1 =
let rec a = function
| `A _ -> true
| `A0 -> false
and b = function
| `B x -> a x
in
a]
|> Parsing_tests.stri_value_binding
|> pass_of_value_binding
in
let any = NPpat_any loc in
let var_x = NPpat_var {txt = "x"; loc} in
[
"catamorphism(1)" >::
begin fun _ ->
let pass =
Parsing_tests.stri_value_binding
[%stri let[@pass Test_L0 => Test_L0] s =
let rec a = function
| `A0 _ -> 0
in 0 ]
|> pass_of_value_binding
in
match TC.catamorphism ~loc ~pass test_L0_a with
| {pexp_desc = Pexp_ident {txt = Lident "a"}} -> ()
| _ -> assert_failure "cata of 'a' has wrong form"
end;
"catamorphism(2)" >::
begin fun _ ->
let pass =
Parsing_tests.stri_value_binding
[%stri let[@pass Test_L0 => Test_L0] s =
let rec b = function
| `B _ -> 0
in 0 ]
|> pass_of_value_binding;
in
try
TC.catamorphism ~loc ~pass test_L0_a
|> ignore;
assert_failure "expected cata for 'a' to fail (not defined)"
with Location.Error _ -> ()
end;
"typeck_pat(1)" >::
begin fun _ ->
assert_equal any (TC.typeck_pat ~pass:pass1 (NP_nonterm "a") any);
assert_equal var_x (TC.typeck_pat ~pass:pass1 (NP_nonterm "b") var_x);
end;
"typeck_pat(2)" >::
begin fun _ ->
let pat = NPpat_variant ("A", Some any, loc) in
assert_equal pat (TC.typeck_pat ~pass:pass1 (NP_nonterm "a") pat);
end;
"typeck_pat(3)" >::
begin fun _ ->
let pat = NPpat_alias (var_x, {txt = "y"; loc}) in
assert_equal pat (TC.typeck_pat ~pass:pass1 (NP_nonterm "a") pat);
assert_equal pat (TC.typeck_pat ~pass:pass1 (NP_term [%type: int]) pat);
end;
"typeck_pat(4)" >::
begin fun _ ->
let pat = NPpat_tuple ([ any; any ], loc) in
assert_equal pat (TC.typeck_pat ~pass:pass1
(NP_tuple [ NP_term [%type: int]; NP_nonterm "a" ])
pat);
end;
"typeck_pat(5)" >::
begin fun _ ->
try
TC.typeck_pat ~pass:pass1
(NP_tuple [ NP_term [%type: int];
NP_nonterm "a" ])
(NPpat_tuple ([ any; any; any ], loc))
|> ignore;
assert_failure "expected bad arg-count tuple to fail"
with Location.Error e ->
assert_equal "wrong number of tuple arguments; expected 2, found 3" e.msg
~printer:(Printf.sprintf "%S")
end;
"typeck_pat(6)" >::
begin fun _ ->
match (TC.typeck_pat ~pass:pass1
(NP_nonterm "a")
(NPpat_cata (var_x, None))) with
| NPpat_cata (NPpat_var {txt = "x"},
Some {pexp_desc =
Pexp_ident {txt = Lident "a"}})
-> ()
| _ -> assert_failure "elaborated (x [@r] : a) has wrong form"
end;
"typeck_pat(7)" >::
begin fun _ ->
match (TC.typeck_pat ~pass:pass1
(NP_list (NP_tuple [ NP_nonterm "a";
NP_term [%type: int] ]))
(NPpat_cata (var_x, None))) with
| NPpat_alias (NPpat_map (NPpat_tuple
([ NPpat_cata (NPpat_any _, Some _);
NPpat_any _ ],
_)),
{txt = "x"}) -> ()
| _ -> assert_failure "elaborated (x [@r] : (a * int) list) has wrong form"
end;
"typeck_nonterm(1)" >::
begin fun _ ->
assert_equal None (TC.typeck_nonterm ~pass:pass1 ~loc "a" "A0" None);
assert_equal (Some var_x) (TC.typeck_nonterm ~pass:pass1 ~loc "a" "A" (Some var_x));
end;
"typeck_nonterm(2)" >::
begin fun _ ->
try
TC.typeck_nonterm ~pass:pass1 ~loc "a" "A0" (Some any)
|> ignore; assert_failure "expected typeck to fail (nonterm doesn't expect arguments)"
with Location.Error e ->
assert_equal "unexpected" (String.sub e.msg 0 10)
~printer:(Printf.sprintf "%S")
end;
"typeck_nonterm(3)" >::
begin fun _ ->
try
TC.typeck_nonterm ~pass:pass1 ~loc "a" "A" None
|> ignore; assert_failure "expected typeck to fail (nonterm expects arguments)"
with Location.Error e ->
assert_equal "expected" (String.sub e.msg 0 8)
~printer:(Printf.sprintf "%S")
end;
"typeck_cata(1)" >::
begin fun _ ->
let cata = [%expr fn a b c] in
assert_equal (`Infer cata)
(TC.typeck_cata ~pass:pass1 ~loc (Some cata) (NP_nonterm "a") any);
assert_equal (`Infer (Exp.ident ~loc {txt = Lident "a"; loc}))
(TC.typeck_cata ~pass:pass1 ~loc None (NP_nonterm "a") any);
assert_equal (`Rewrite any)
(TC.typeck_cata ~pass:pass1 ~loc None (NP_term [%type: int]) any);
end;
"typeck_cata(2)" >::
begin fun _ ->
match TC.typeck_cata ~pass:pass1 ~loc None
(NP_tuple [ NP_term [%type: int]; NP_nonterm "a" ])
any
with
| `Rewrite (NPpat_tuple ([ NPpat_cata (_, None);
NPpat_cata (_, None) ], _)) -> ()
| _ -> assert_failure "rewritten tuple has wrong form"
end;
"typeck_cata(3)" >::
begin fun _ ->
match TC.typeck_cata ~pass:pass1 ~loc None
(NP_tuple [ NP_term [%type: int]; NP_nonterm "a" ])
var_x
with
| `Rewrite (NPpat_alias
(NPpat_tuple ([ NPpat_cata (_, None);
NPpat_cata (_, None) ], _),
{txt = "x"})) -> ()
| _ -> assert_failure "rewritten tuple (+ alias) has wrong form"
end;
"typeck_cata(4)" >::
begin fun _ ->
let cata = [%expr fn a b c] in
match TC.typeck_cata ~pass:pass1 ~loc (Some cata)
(NP_list (NP_nonterm "a"))
any
with
| `Rewrite (NPpat_map (NPpat_cata (NPpat_any _, Some _))) -> ()
| _ -> assert_failure "rewritten list has wrong form"
end;
"typeck_cata(5)" >::
begin fun _ ->
try
TC.typeck_cata ~pass:pass1 ~loc None
(NP_nonterm "a")
(NPpat_variant ("A", None, loc))
|> ignore;
assert_failure "expected non-total pattern in cata result to fail"
with Location.Error _ -> ()
end;
]
|
926660d398b440178959342b2082f560d9957fa4234d8e9d1e3b5b142deb1a65 | portkey-cloud/aws-clj-sdk | _2016-06-27.clj | (ns portkey.aws.rekognition.-2016-06-27 (:require [portkey.aws]))
(def
endpoints
'{"ap-northeast-1"
{:credential-scope
{:service "rekognition", :region "ap-northeast-1"},
:ssl-common-name "rekognition.ap-northeast-1.amazonaws.com",
:endpoint "-northeast-1.amazonaws.com",
:signature-version :v4},
"eu-west-1"
{:credential-scope {:service "rekognition", :region "eu-west-1"},
:ssl-common-name "rekognition.eu-west-1.amazonaws.com",
:endpoint "-west-1.amazonaws.com",
:signature-version :v4},
"us-east-2"
{:credential-scope {:service "rekognition", :region "us-east-2"},
:ssl-common-name "rekognition.us-east-2.amazonaws.com",
:endpoint "-east-2.amazonaws.com",
:signature-version :v4},
"ap-southeast-2"
{:credential-scope
{:service "rekognition", :region "ap-southeast-2"},
:ssl-common-name "rekognition.ap-southeast-2.amazonaws.com",
:endpoint "-southeast-2.amazonaws.com",
:signature-version :v4},
"us-west-2"
{:credential-scope {:service "rekognition", :region "us-west-2"},
:ssl-common-name "rekognition.us-west-2.amazonaws.com",
:endpoint "-west-2.amazonaws.com",
:signature-version :v4},
"us-east-1"
{:credential-scope {:service "rekognition", :region "us-east-1"},
:ssl-common-name "rekognition.us-east-1.amazonaws.com",
:endpoint "-east-1.amazonaws.com",
:signature-version :v4},
"us-gov-west-1"
{:credential-scope
{:service "rekognition", :region "us-gov-west-1"},
:ssl-common-name "rekognition.us-gov-west-1.amazonaws.com",
:endpoint "-gov-west-1.amazonaws.com",
:signature-version :v4}})
(comment TODO support "json")
| null | https://raw.githubusercontent.com/portkey-cloud/aws-clj-sdk/10623a5c86bd56c8b312f56b76ae5ff52c26a945/src/portkey/aws/rekognition/_2016-06-27.clj | clojure | (ns portkey.aws.rekognition.-2016-06-27 (:require [portkey.aws]))
(def
endpoints
'{"ap-northeast-1"
{:credential-scope
{:service "rekognition", :region "ap-northeast-1"},
:ssl-common-name "rekognition.ap-northeast-1.amazonaws.com",
:endpoint "-northeast-1.amazonaws.com",
:signature-version :v4},
"eu-west-1"
{:credential-scope {:service "rekognition", :region "eu-west-1"},
:ssl-common-name "rekognition.eu-west-1.amazonaws.com",
:endpoint "-west-1.amazonaws.com",
:signature-version :v4},
"us-east-2"
{:credential-scope {:service "rekognition", :region "us-east-2"},
:ssl-common-name "rekognition.us-east-2.amazonaws.com",
:endpoint "-east-2.amazonaws.com",
:signature-version :v4},
"ap-southeast-2"
{:credential-scope
{:service "rekognition", :region "ap-southeast-2"},
:ssl-common-name "rekognition.ap-southeast-2.amazonaws.com",
:endpoint "-southeast-2.amazonaws.com",
:signature-version :v4},
"us-west-2"
{:credential-scope {:service "rekognition", :region "us-west-2"},
:ssl-common-name "rekognition.us-west-2.amazonaws.com",
:endpoint "-west-2.amazonaws.com",
:signature-version :v4},
"us-east-1"
{:credential-scope {:service "rekognition", :region "us-east-1"},
:ssl-common-name "rekognition.us-east-1.amazonaws.com",
:endpoint "-east-1.amazonaws.com",
:signature-version :v4},
"us-gov-west-1"
{:credential-scope
{:service "rekognition", :region "us-gov-west-1"},
:ssl-common-name "rekognition.us-gov-west-1.amazonaws.com",
:endpoint "-gov-west-1.amazonaws.com",
:signature-version :v4}})
(comment TODO support "json")
| |
83487f6c7c24f253c8901db6af7a2fbcc1545fa60bc9ca5e19bd79c766fed8b4 | ghc/ghc | Equality.hs | {-# LANGUAGE DataKinds #-}
# LANGUAGE FlexibleInstances #
{-# LANGUAGE GADTs #-}
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE PolyKinds #
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE StandaloneDeriving #-}
# LANGUAGE StandaloneKindSignatures #
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
# LANGUAGE UndecidableInstances #
-----------------------------------------------------------------------------
-- |
-- Module : Data.Type.Equality
-- License : BSD-style (see the LICENSE file in the distribution)
--
-- Maintainer :
-- Stability : stable
-- Portability : not portable
--
-- Definition of propositional equality @(':~:')@. Pattern-matching on a variable
of type @(a ' : ~ : ' b)@ produces a proof that @a ' ~ ' b@.
--
-- @since 4.7.0.0
-----------------------------------------------------------------------------
module Data.Type.Equality (
-- * The equality types
type (~),
type (~~),
(:~:)(..),
(:~~:)(..),
-- * Working with equality
sym, trans, castWith, gcastWith, apply, inner, outer,
-- * Inferring equality from other types
TestEquality(..),
-- * Boolean type-level equality
type (==)
) where
import Data.Maybe
import GHC.Enum
import GHC.Show
import GHC.Read
import GHC.Base
import Data.Type.Bool
infix 4 :~:, :~~:
| Propositional equality . If @a : ~ : is inhabited by some terminating
value , then the type @a@ is the same as the type @b@. To use this equality
in practice , pattern - match on the @a : ~ : b@ to get out the @Refl@ constructor ;
in the body of the pattern - match , the compiler knows that @a ~ b@.
--
-- @since 4.7.0.0
See Note [ The equality types story ] in GHC.Builtin . Types . Prim
Refl :: a :~: a
with credit to for ' ty ' ,
Steenbergen for ' type - equality ' , for ' eq ' , and
-- for 'type-eq'
-- | Symmetry of equality
sym :: (a :~: b) -> (b :~: a)
sym Refl = Refl
-- | Transitivity of equality
trans :: (a :~: b) -> (b :~: c) -> (a :~: c)
trans Refl Refl = Refl
-- | Type-safe cast, using propositional equality
castWith :: (a :~: b) -> a -> b
castWith Refl x = x
-- | Generalized form of type-safe cast using propositional equality
gcastWith :: (a :~: b) -> ((a ~ b) => r) -> r
gcastWith Refl x = x
| Apply one equality to another , respectively
apply :: (f :~: g) -> (a :~: b) -> (f a :~: g b)
apply Refl Refl = Refl
-- | Extract equality of the arguments from an equality of applied types
inner :: (f a :~: g b) -> (a :~: b)
inner Refl = Refl
-- | Extract equality of type constructors from an equality of applied types
outer :: (f a :~: g b) -> (f :~: g)
outer Refl = Refl
| @since 4.7.0.0
deriving instance Eq (a :~: b)
| @since 4.7.0.0
deriving instance Show (a :~: b)
| @since 4.7.0.0
deriving instance Ord (a :~: b)
| @since 4.7.0.0
deriving instance a ~ b => Read (a :~: b)
| @since 4.7.0.0
instance a ~ b => Enum (a :~: b) where
toEnum 0 = Refl
toEnum _ = errorWithoutStackTrace "Data.Type.Equality.toEnum: bad argument"
fromEnum Refl = 0
| @since 4.7.0.0
deriving instance a ~ b => Bounded (a :~: b)
| Kind heterogeneous propositional equality . Like ' : ~ : ' , @a : ~~ : b@ is
inhabited by a terminating value if and only if @a@ is the same type as @b@.
--
@since 4.10.0.0
type (:~~:) :: k1 -> k2 -> Type
data a :~~: b where
HRefl :: a :~~: a
| @since 4.10.0.0
deriving instance Eq (a :~~: b)
| @since 4.10.0.0
deriving instance Show (a :~~: b)
| @since 4.10.0.0
deriving instance Ord (a :~~: b)
| @since 4.10.0.0
deriving instance a ~~ b => Read (a :~~: b)
| @since 4.10.0.0
instance a ~~ b => Enum (a :~~: b) where
toEnum 0 = HRefl
toEnum _ = errorWithoutStackTrace "Data.Type.Equality.toEnum: bad argument"
fromEnum HRefl = 0
| @since 4.10.0.0
deriving instance a ~~ b => Bounded (a :~~: b)
| This class contains types where you can learn the equality of two types
-- from information contained in /terms/.
--
The result should be @Just Refl@ if and only if the types applied to @f@ are
-- equal:
--
-- @testEquality (x :: f a) (y :: f b) = Just Refl ⟺ a = b@
--
-- Typically, only singleton types should inhabit this class. In that case type
-- argument equality coincides with term equality:
--
-- @testEquality (x :: f a) (y :: f b) = Just Refl ⟺ a = b ⟺ x = y@
--
-- @isJust (testEquality x y) = x == y@
--
Singleton types are not required , however , and so the latter two would - be
-- laws are not in fact valid in general.
class TestEquality f where
| Conditionally prove the equality of @a@ and
testEquality :: f a -> f b -> Maybe (a :~: b)
| @since 4.7.0.0
instance TestEquality ((:~:) a) where
testEquality Refl Refl = Just Refl
| @since 4.10.0.0
instance TestEquality ((:~~:) a) where
testEquality HRefl HRefl = Just Refl
infix 4 ==
| A type family to compute Boolean equality .
type (==) :: k -> k -> Bool
type family a == b where
f a == g b = f == g && a == b
a == a = 'True
_ == _ = 'False
-- The idea here is to recognize equality of *applications* using
the first case , and of * constructors * using the second and third
ones . It would be wonderful if GHC recognized that the
first and second cases are compatible , which would allow us to
-- prove
--
-- a ~ b => a == b
--
-- but it (understandably) does not.
--
It is absolutely critical that the three cases occur in precisely
-- this order. In particular, if
--
-- a == a = 'True
--
came first , then the type application case would only be reached
( uselessly ) when GHC discovered that the types were not equal .
--
-- One might reasonably ask what's wrong with a simpler version:
--
-- type family (a :: k) == (b :: k) where
-- a == a = True
-- a == b = False
--
-- Consider
data Succ Nat
--
-- Suppose I want
-- foo :: (Succ n == Succ m) ~ True => ((n == m) :~: True)
-- foo = Refl
--
-- This would not type-check with the simple version. `Succ n == Succ m`
-- is stuck. We don't know enough about `n` and `m` to reduce the family.
-- With the recursive version, `Succ n == Succ m` reduces to
` Succ = = Succ & & n = = m ` , which can reduce to ` ' True & & n = = m ` and
-- finally to `n == m`.
| null | https://raw.githubusercontent.com/ghc/ghc/37cfe3c0f4fb16189bbe3bb735f758cd6e3d9157/libraries/base/Data/Type/Equality.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE GADTs #
# LANGUAGE RankNTypes #
# LANGUAGE StandaloneDeriving #
# LANGUAGE Trustworthy #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
---------------------------------------------------------------------------
|
Module : Data.Type.Equality
License : BSD-style (see the LICENSE file in the distribution)
Maintainer :
Stability : stable
Portability : not portable
Definition of propositional equality @(':~:')@. Pattern-matching on a variable
@since 4.7.0.0
---------------------------------------------------------------------------
* The equality types
* Working with equality
* Inferring equality from other types
* Boolean type-level equality
@since 4.7.0.0
for 'type-eq'
| Symmetry of equality
| Transitivity of equality
| Type-safe cast, using propositional equality
| Generalized form of type-safe cast using propositional equality
| Extract equality of the arguments from an equality of applied types
| Extract equality of type constructors from an equality of applied types
from information contained in /terms/.
equal:
@testEquality (x :: f a) (y :: f b) = Just Refl ⟺ a = b@
Typically, only singleton types should inhabit this class. In that case type
argument equality coincides with term equality:
@testEquality (x :: f a) (y :: f b) = Just Refl ⟺ a = b ⟺ x = y@
@isJust (testEquality x y) = x == y@
laws are not in fact valid in general.
The idea here is to recognize equality of *applications* using
prove
a ~ b => a == b
but it (understandably) does not.
this order. In particular, if
a == a = 'True
One might reasonably ask what's wrong with a simpler version:
type family (a :: k) == (b :: k) where
a == a = True
a == b = False
Consider
Suppose I want
foo :: (Succ n == Succ m) ~ True => ((n == m) :~: True)
foo = Refl
This would not type-check with the simple version. `Succ n == Succ m`
is stuck. We don't know enough about `n` and `m` to reduce the family.
With the recursive version, `Succ n == Succ m` reduces to
finally to `n == m`. | # LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE PolyKinds #
# LANGUAGE StandaloneKindSignatures #
# LANGUAGE UndecidableInstances #
of type @(a ' : ~ : ' b)@ produces a proof that @a ' ~ ' b@.
module Data.Type.Equality (
type (~),
type (~~),
(:~:)(..),
(:~~:)(..),
sym, trans, castWith, gcastWith, apply, inner, outer,
TestEquality(..),
type (==)
) where
import Data.Maybe
import GHC.Enum
import GHC.Show
import GHC.Read
import GHC.Base
import Data.Type.Bool
infix 4 :~:, :~~:
| Propositional equality . If @a : ~ : is inhabited by some terminating
value , then the type @a@ is the same as the type @b@. To use this equality
in practice , pattern - match on the @a : ~ : b@ to get out the @Refl@ constructor ;
in the body of the pattern - match , the compiler knows that @a ~ b@.
See Note [ The equality types story ] in GHC.Builtin . Types . Prim
Refl :: a :~: a
with credit to for ' ty ' ,
Steenbergen for ' type - equality ' , for ' eq ' , and
sym :: (a :~: b) -> (b :~: a)
sym Refl = Refl
trans :: (a :~: b) -> (b :~: c) -> (a :~: c)
trans Refl Refl = Refl
castWith :: (a :~: b) -> a -> b
castWith Refl x = x
gcastWith :: (a :~: b) -> ((a ~ b) => r) -> r
gcastWith Refl x = x
| Apply one equality to another , respectively
apply :: (f :~: g) -> (a :~: b) -> (f a :~: g b)
apply Refl Refl = Refl
inner :: (f a :~: g b) -> (a :~: b)
inner Refl = Refl
outer :: (f a :~: g b) -> (f :~: g)
outer Refl = Refl
| @since 4.7.0.0
deriving instance Eq (a :~: b)
| @since 4.7.0.0
deriving instance Show (a :~: b)
| @since 4.7.0.0
deriving instance Ord (a :~: b)
| @since 4.7.0.0
deriving instance a ~ b => Read (a :~: b)
| @since 4.7.0.0
instance a ~ b => Enum (a :~: b) where
toEnum 0 = Refl
toEnum _ = errorWithoutStackTrace "Data.Type.Equality.toEnum: bad argument"
fromEnum Refl = 0
| @since 4.7.0.0
deriving instance a ~ b => Bounded (a :~: b)
| Kind heterogeneous propositional equality . Like ' : ~ : ' , @a : ~~ : b@ is
inhabited by a terminating value if and only if @a@ is the same type as @b@.
@since 4.10.0.0
type (:~~:) :: k1 -> k2 -> Type
data a :~~: b where
HRefl :: a :~~: a
| @since 4.10.0.0
deriving instance Eq (a :~~: b)
| @since 4.10.0.0
deriving instance Show (a :~~: b)
| @since 4.10.0.0
deriving instance Ord (a :~~: b)
| @since 4.10.0.0
deriving instance a ~~ b => Read (a :~~: b)
| @since 4.10.0.0
instance a ~~ b => Enum (a :~~: b) where
toEnum 0 = HRefl
toEnum _ = errorWithoutStackTrace "Data.Type.Equality.toEnum: bad argument"
fromEnum HRefl = 0
| @since 4.10.0.0
deriving instance a ~~ b => Bounded (a :~~: b)
| This class contains types where you can learn the equality of two types
The result should be @Just Refl@ if and only if the types applied to @f@ are
Singleton types are not required , however , and so the latter two would - be
class TestEquality f where
| Conditionally prove the equality of @a@ and
testEquality :: f a -> f b -> Maybe (a :~: b)
| @since 4.7.0.0
instance TestEquality ((:~:) a) where
testEquality Refl Refl = Just Refl
| @since 4.10.0.0
instance TestEquality ((:~~:) a) where
testEquality HRefl HRefl = Just Refl
infix 4 ==
| A type family to compute Boolean equality .
type (==) :: k -> k -> Bool
type family a == b where
f a == g b = f == g && a == b
a == a = 'True
_ == _ = 'False
the first case , and of * constructors * using the second and third
ones . It would be wonderful if GHC recognized that the
first and second cases are compatible , which would allow us to
It is absolutely critical that the three cases occur in precisely
came first , then the type application case would only be reached
( uselessly ) when GHC discovered that the types were not equal .
data Succ Nat
` Succ = = Succ & & n = = m ` , which can reduce to ` ' True & & n = = m ` and
|
6efebae21697fc30f2a6ead3cc4732fcce4ea650babcbe7485cb48ab2a5271c3 | project-oak/hafnium-verification | PhysEqual.mli |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
val shallow_equal : 'a -> 'a -> bool
* Helpers function to enforce physical equality .
Let suppose [ construct / deconstruct ] is a 1 - level - allocation OCaml construction / deconstruction ,
such as variant type , tuple or record construction . Instead of writing
{ [
let a = deconstruct a0 in
let b = deconstruct b0 in
let res = f a b in
if phys_equal res a then a0 else if phys_equal res b then b0 else construct res
] }
Simply write
{ [ ~res:(construct ( f a b ) ) a0 b0 ] }
Let suppose [construct/deconstruct] is a 1-level-allocation OCaml construction/deconstruction,
such as variant type, tuple or record construction. Instead of writing
{[
let a = deconstruct a0 in
let b = deconstruct b0 in
let res = f a b in
if phys_equal res a then a0 else if phys_equal res b then b0 else construct res
]}
Simply write
{[ PhysEqual.optim2 ~res:(construct (f a b)) a0 b0 ]} *)
val optim1 : res:'a -> 'a -> 'a
val optim2 : res:'a -> 'a -> 'a -> 'a
| null | https://raw.githubusercontent.com/project-oak/hafnium-verification/6071eff162148e4d25a0fedaea003addac242ace/experiments/ownership-inference/infer/infer/src/istd/PhysEqual.mli | ocaml |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
val shallow_equal : 'a -> 'a -> bool
* Helpers function to enforce physical equality .
Let suppose [ construct / deconstruct ] is a 1 - level - allocation OCaml construction / deconstruction ,
such as variant type , tuple or record construction . Instead of writing
{ [
let a = deconstruct a0 in
let b = deconstruct b0 in
let res = f a b in
if phys_equal res a then a0 else if phys_equal res b then b0 else construct res
] }
Simply write
{ [ ~res:(construct ( f a b ) ) a0 b0 ] }
Let suppose [construct/deconstruct] is a 1-level-allocation OCaml construction/deconstruction,
such as variant type, tuple or record construction. Instead of writing
{[
let a = deconstruct a0 in
let b = deconstruct b0 in
let res = f a b in
if phys_equal res a then a0 else if phys_equal res b then b0 else construct res
]}
Simply write
{[ PhysEqual.optim2 ~res:(construct (f a b)) a0 b0 ]} *)
val optim1 : res:'a -> 'a -> 'a
val optim2 : res:'a -> 'a -> 'a -> 'a
| |
b2b161a4f0752f3dd93d4a59cb493baaf98c5e1ed268b69d11ea9a47b377de78 | pqwy/lru | test.ml | Copyright ( c ) 2016 . All rights reserved .
See LICENSE.md
See LICENSE.md *)
let id x = x
let (%) f g x = f (g x)
module I = struct
type t = int
let compare (a: int) b = compare a b
let equal (a: int) b = a = b
let hash (i: int) = Hashtbl.hash i
let weight _ = 1
end
let sort_uniq_r (type a) cmp xs =
let module S = Set.Make (struct type t = a let compare = cmp end) in
List.fold_right S.add xs S.empty |> S.elements
let uniq_r (type a) cmp xs =
let module S = Set.Make (struct type t = a let compare = cmp end) in
let rec go s acc = function
[] -> acc
| x::xs -> if S.mem x s then go s acc xs else go (S.add x s) (x :: acc) xs in
go S.empty [] (List.rev xs)
let list_of_iter_2 i =
let xs = ref [] in i (fun a b -> xs := (a, b) :: !xs); List.rev !xs
let list_trim w xs =
let rec go wacc acc = function
[] -> acc
| kv::xs -> let w' = I.weight (snd kv) + wacc in
if w' <= w then go w' (kv::acc) xs else acc in
go 0 [] (List.rev xs)
let list_weight = List.fold_left (fun a (_, v) -> a + I.weight v) 0
let cmpi (a: int) b = compare a b
let cmp_k (k1, _) (k2, _) = cmpi k1 k2
let sorted_by_k xs = List.sort cmp_k xs
let size = QCheck.Gen.(small_nat >|= fun x -> x mod 1_000)
let bindings = QCheck.(
make Gen.(list_size size (pair small_nat small_nat))
~print:Fmt.(to_to_string Fmt.(Dump.(list (pair int int))))
~shrink:Shrink.list)
let test name gen p =
QCheck.Test.make ~name gen p |> QCheck_alcotest.to_alcotest
module F = Lru.F.Make (I) (I)
let pp_f = Fmt.(F.pp_dump int int)
let (!) f = `Sem F.(to_list f, size f, weight f)
let sem xs = `Sem List.(xs, length xs, list_weight xs)
let lru = QCheck.(
map F.of_list bindings ~rev:F.to_list |>
set_print Fmt.(to_to_string pp_f))
let lru_w_nat = QCheck.(pair lru small_nat)
let () = Alcotest.run ~and_exit:false "Lru.F" [
"of_list", [
test "sem" bindings
(fun xs -> !F.(of_list xs) = sem (uniq_r cmp_k xs));
test "cap" bindings
(fun xs -> F.(capacity (of_list xs)) = list_weight (uniq_r cmp_k xs));
];
"membership", [
test "find sem" lru_w_nat
(fun (m, x) -> F.find x m = List.assoc_opt x (F.to_list m));
test "mem ==> find" lru_w_nat
(fun (m, e) -> QCheck.assume (F.mem e m); F.find e m <> None);
test "find ==> mem" lru_w_nat
(fun (m, e) -> QCheck.assume (F.find e m <> None); F.mem e m);
];
"add", [
test "sem" lru_w_nat
(fun (m, k) ->
!(F.add k k m) = sem (List.remove_assoc k (F.to_list m) @ [k, k]));
];
"remove", [
test "sem" lru_w_nat
(fun (m, k) -> !(F.remove k m) = sem (List.remove_assoc k (F.to_list m)));
];
"trim", [
test "sem" lru_w_nat
(fun (m, x) ->
!F.(resize x m |> trim) = sem (list_trim x (F.to_list m)));
];
"promote", [
test "sem" lru_w_nat
(fun (m, x) ->
!(F.promote x m) =
!(match F.find x m with Some v -> F.add x v m | _ -> m));
];
"lru", [
test "lru sem" lru
(fun m ->
QCheck.assume (F.size m > 0);
F.lru m = Some (List.hd (F.to_list m)));
test "drop_lru sem" lru
(fun m ->
QCheck.assume (F.size m > 0);
F.(to_list (drop_lru m) = List.tl (F.to_list m)));
];
"conv", [
test "to_list inv" lru (fun m -> !F.(of_list (to_list m)) = !m);
test "to_list = fold" lru
(fun m -> F.to_list m = F.fold (fun k v a -> (k, v)::a) [] m);
test "to_list = iter" lru
(fun m -> list_of_iter_2 (fun f -> F.iter f m) = F.to_list m);
test "fold_k sem" lru
(fun m ->
F.fold_k (fun k v a -> (k, v)::a) [] m = sorted_by_k (F.to_list m));
test "iter_k sem" lru
(fun m ->
list_of_iter_2 (fun f -> F.iter_k f m) = sorted_by_k (F.to_list m));
]
]
module M = Lru.M.Make (I) (I)
let pp_m = Fmt.(M.pp_dump int int)
let (!!) m = `Sem M.(to_list m, size m, weight m)
let lru = QCheck.(
map M.of_list bindings ~rev:M.to_list |>
set_print Fmt.(to_to_string pp_m))
let lru_w_nat = QCheck.(pair lru small_nat)
let lrus = QCheck.(
map (fun xs -> M.of_list xs, F.of_list xs) ~rev:(F.to_list % snd) bindings
|> set_print Fmt.(to_to_string pp_f % snd))
let lrus_w_nat = QCheck.(pair lrus small_nat)
let () = Alcotest.run "Lru.M" [
"of_list", [
test "sem" bindings
(fun xs -> !!M.(of_list xs) = sem (uniq_r cmp_k xs));
test "cap" bindings
(fun xs -> M.(capacity (of_list xs)) = list_weight (uniq_r cmp_k xs));
];
"membership", [
test "find" lrus_w_nat (fun ((m, f), x) -> M.find x m = F.find x f);
test "mem" lrus_w_nat (fun ((m, f), x) -> M.mem x m = F.mem x f);
];
"add", [
test "eqv" lrus_w_nat
(fun ((m, f), x) -> M.add x x m; !!m = !(F.add x x f))
];
"remove", [
test "eqv" lrus_w_nat
(fun ((m, f), x) -> M.remove x m; !!m = !(F.remove x f));
];
"trim", [
test "eqv" lrus_w_nat
(fun ((m, f), x) ->
M.resize x m; M.trim m; !!m = !F.(resize x f |> trim));
];
"promote", [
test "eqv" lrus_w_nat
(fun ((m, f), x) -> M.promote x m; !!m = !(F.promote x f));
];
"lru", [
test "eqv" lrus (fun (m, f) -> M.lru m = F.lru f);
test "drop eqv" lrus (fun (m, f) -> M.drop_lru m; !!m = !F.(drop_lru f));
];
"conv", [
test "to_list inv" lru (fun m -> !!M.(of_list (to_list m)) = !!m);
test "to_list = fold" lru
(fun m -> M.fold (fun k v a -> (k, v)::a) [] m = M.to_list m);
test "to_list = iter" lru
(fun m -> list_of_iter_2 (fun f -> M.iter f m) = M.to_list m)
];
"pp", [
test "eqv" lrus
(fun (m, f) -> Fmt.(to_to_string pp_m m = to_to_string pp_f f));
]
]
| null | https://raw.githubusercontent.com/pqwy/lru/b88a102bcb14c900c4233c47202678e948181009/test/test.ml | ocaml | Copyright ( c ) 2016 . All rights reserved .
See LICENSE.md
See LICENSE.md *)
let id x = x
let (%) f g x = f (g x)
module I = struct
type t = int
let compare (a: int) b = compare a b
let equal (a: int) b = a = b
let hash (i: int) = Hashtbl.hash i
let weight _ = 1
end
let sort_uniq_r (type a) cmp xs =
let module S = Set.Make (struct type t = a let compare = cmp end) in
List.fold_right S.add xs S.empty |> S.elements
let uniq_r (type a) cmp xs =
let module S = Set.Make (struct type t = a let compare = cmp end) in
let rec go s acc = function
[] -> acc
| x::xs -> if S.mem x s then go s acc xs else go (S.add x s) (x :: acc) xs in
go S.empty [] (List.rev xs)
let list_of_iter_2 i =
let xs = ref [] in i (fun a b -> xs := (a, b) :: !xs); List.rev !xs
let list_trim w xs =
let rec go wacc acc = function
[] -> acc
| kv::xs -> let w' = I.weight (snd kv) + wacc in
if w' <= w then go w' (kv::acc) xs else acc in
go 0 [] (List.rev xs)
let list_weight = List.fold_left (fun a (_, v) -> a + I.weight v) 0
let cmpi (a: int) b = compare a b
let cmp_k (k1, _) (k2, _) = cmpi k1 k2
let sorted_by_k xs = List.sort cmp_k xs
let size = QCheck.Gen.(small_nat >|= fun x -> x mod 1_000)
let bindings = QCheck.(
make Gen.(list_size size (pair small_nat small_nat))
~print:Fmt.(to_to_string Fmt.(Dump.(list (pair int int))))
~shrink:Shrink.list)
let test name gen p =
QCheck.Test.make ~name gen p |> QCheck_alcotest.to_alcotest
module F = Lru.F.Make (I) (I)
let pp_f = Fmt.(F.pp_dump int int)
let (!) f = `Sem F.(to_list f, size f, weight f)
let sem xs = `Sem List.(xs, length xs, list_weight xs)
let lru = QCheck.(
map F.of_list bindings ~rev:F.to_list |>
set_print Fmt.(to_to_string pp_f))
let lru_w_nat = QCheck.(pair lru small_nat)
let () = Alcotest.run ~and_exit:false "Lru.F" [
"of_list", [
test "sem" bindings
(fun xs -> !F.(of_list xs) = sem (uniq_r cmp_k xs));
test "cap" bindings
(fun xs -> F.(capacity (of_list xs)) = list_weight (uniq_r cmp_k xs));
];
"membership", [
test "find sem" lru_w_nat
(fun (m, x) -> F.find x m = List.assoc_opt x (F.to_list m));
test "mem ==> find" lru_w_nat
(fun (m, e) -> QCheck.assume (F.mem e m); F.find e m <> None);
test "find ==> mem" lru_w_nat
(fun (m, e) -> QCheck.assume (F.find e m <> None); F.mem e m);
];
"add", [
test "sem" lru_w_nat
(fun (m, k) ->
!(F.add k k m) = sem (List.remove_assoc k (F.to_list m) @ [k, k]));
];
"remove", [
test "sem" lru_w_nat
(fun (m, k) -> !(F.remove k m) = sem (List.remove_assoc k (F.to_list m)));
];
"trim", [
test "sem" lru_w_nat
(fun (m, x) ->
!F.(resize x m |> trim) = sem (list_trim x (F.to_list m)));
];
"promote", [
test "sem" lru_w_nat
(fun (m, x) ->
!(F.promote x m) =
!(match F.find x m with Some v -> F.add x v m | _ -> m));
];
"lru", [
test "lru sem" lru
(fun m ->
QCheck.assume (F.size m > 0);
F.lru m = Some (List.hd (F.to_list m)));
test "drop_lru sem" lru
(fun m ->
QCheck.assume (F.size m > 0);
F.(to_list (drop_lru m) = List.tl (F.to_list m)));
];
"conv", [
test "to_list inv" lru (fun m -> !F.(of_list (to_list m)) = !m);
test "to_list = fold" lru
(fun m -> F.to_list m = F.fold (fun k v a -> (k, v)::a) [] m);
test "to_list = iter" lru
(fun m -> list_of_iter_2 (fun f -> F.iter f m) = F.to_list m);
test "fold_k sem" lru
(fun m ->
F.fold_k (fun k v a -> (k, v)::a) [] m = sorted_by_k (F.to_list m));
test "iter_k sem" lru
(fun m ->
list_of_iter_2 (fun f -> F.iter_k f m) = sorted_by_k (F.to_list m));
]
]
module M = Lru.M.Make (I) (I)
let pp_m = Fmt.(M.pp_dump int int)
let (!!) m = `Sem M.(to_list m, size m, weight m)
let lru = QCheck.(
map M.of_list bindings ~rev:M.to_list |>
set_print Fmt.(to_to_string pp_m))
let lru_w_nat = QCheck.(pair lru small_nat)
let lrus = QCheck.(
map (fun xs -> M.of_list xs, F.of_list xs) ~rev:(F.to_list % snd) bindings
|> set_print Fmt.(to_to_string pp_f % snd))
let lrus_w_nat = QCheck.(pair lrus small_nat)
let () = Alcotest.run "Lru.M" [
"of_list", [
test "sem" bindings
(fun xs -> !!M.(of_list xs) = sem (uniq_r cmp_k xs));
test "cap" bindings
(fun xs -> M.(capacity (of_list xs)) = list_weight (uniq_r cmp_k xs));
];
"membership", [
test "find" lrus_w_nat (fun ((m, f), x) -> M.find x m = F.find x f);
test "mem" lrus_w_nat (fun ((m, f), x) -> M.mem x m = F.mem x f);
];
"add", [
test "eqv" lrus_w_nat
(fun ((m, f), x) -> M.add x x m; !!m = !(F.add x x f))
];
"remove", [
test "eqv" lrus_w_nat
(fun ((m, f), x) -> M.remove x m; !!m = !(F.remove x f));
];
"trim", [
test "eqv" lrus_w_nat
(fun ((m, f), x) ->
M.resize x m; M.trim m; !!m = !F.(resize x f |> trim));
];
"promote", [
test "eqv" lrus_w_nat
(fun ((m, f), x) -> M.promote x m; !!m = !(F.promote x f));
];
"lru", [
test "eqv" lrus (fun (m, f) -> M.lru m = F.lru f);
test "drop eqv" lrus (fun (m, f) -> M.drop_lru m; !!m = !F.(drop_lru f));
];
"conv", [
test "to_list inv" lru (fun m -> !!M.(of_list (to_list m)) = !!m);
test "to_list = fold" lru
(fun m -> M.fold (fun k v a -> (k, v)::a) [] m = M.to_list m);
test "to_list = iter" lru
(fun m -> list_of_iter_2 (fun f -> M.iter f m) = M.to_list m)
];
"pp", [
test "eqv" lrus
(fun (m, f) -> Fmt.(to_to_string pp_m m = to_to_string pp_f f));
]
]
| |
6fcd410b222b42d98e463169dd93794ab4609efcd289f8cff153478ba6666a34 | int-index/kalium | Pattern.hs | # LANGUAGE FlexibleContexts #
module Kalium.Nucleus.Vector.Pattern where
import qualified Data.Set as S
import Control.Monad.Writer
import Kalium.Prelude
import Kalium.Nucleus.Vector.Program
patBound :: Pattern -> Set Name
patBound = \case
PWildCard -> mempty
PUnit -> mempty
PAccess name _ -> S.singleton name
PTuple p1 p2 -> patBound p1 <> patBound p2
PExt pext -> absurd pext
patRemoveUnits :: MonadWriter (Set Name) m => Pattern -> m Pattern
patRemoveUnits = \case
PWildCard -> return PWildCard
PUnit -> return PWildCard
PAccess name TypeUnit -> do
tell (S.singleton name)
return PWildCard
p@(PAccess _ _) -> return p
PTuple p1 p2 -> liftM2 PTuple (patRemoveUnits p1) (patRemoveUnits p2)
PExt pext -> absurd pext
patType :: Pattern -> Maybe Type
patType = \case
PWildCard -> Nothing
PUnit -> return TypeUnit
PAccess _ ty -> return ty
PTuple p1 p2 -> liftM2 (TypeApp2 TypePair) (patType p1) (patType p2)
PExt pext -> absurd pext
patIsAccess (PAccess _ _) = True
patIsAccess _ = False
preciseMatch :: Pattern -> Expression -> Bool
preciseMatch = \case
PWildCard -> const False
PUnit -> (==) LitUnit
PAccess name1 _ -> \case
Access name2 | name1 == name2 -> True
_ -> False
PTuple p1 p2 -> \case
App2 (OpAccess OpPair) e1 e2 -> preciseMatch p1 e1 && preciseMatch p2 e2
_ -> False
PExt pext -> absurd pext
| null | https://raw.githubusercontent.com/int-index/kalium/0653b4229001880322acf3016de595360de726ec/src/Kalium/Nucleus/Vector/Pattern.hs | haskell | # LANGUAGE FlexibleContexts #
module Kalium.Nucleus.Vector.Pattern where
import qualified Data.Set as S
import Control.Monad.Writer
import Kalium.Prelude
import Kalium.Nucleus.Vector.Program
patBound :: Pattern -> Set Name
patBound = \case
PWildCard -> mempty
PUnit -> mempty
PAccess name _ -> S.singleton name
PTuple p1 p2 -> patBound p1 <> patBound p2
PExt pext -> absurd pext
patRemoveUnits :: MonadWriter (Set Name) m => Pattern -> m Pattern
patRemoveUnits = \case
PWildCard -> return PWildCard
PUnit -> return PWildCard
PAccess name TypeUnit -> do
tell (S.singleton name)
return PWildCard
p@(PAccess _ _) -> return p
PTuple p1 p2 -> liftM2 PTuple (patRemoveUnits p1) (patRemoveUnits p2)
PExt pext -> absurd pext
patType :: Pattern -> Maybe Type
patType = \case
PWildCard -> Nothing
PUnit -> return TypeUnit
PAccess _ ty -> return ty
PTuple p1 p2 -> liftM2 (TypeApp2 TypePair) (patType p1) (patType p2)
PExt pext -> absurd pext
patIsAccess (PAccess _ _) = True
patIsAccess _ = False
preciseMatch :: Pattern -> Expression -> Bool
preciseMatch = \case
PWildCard -> const False
PUnit -> (==) LitUnit
PAccess name1 _ -> \case
Access name2 | name1 == name2 -> True
_ -> False
PTuple p1 p2 -> \case
App2 (OpAccess OpPair) e1 e2 -> preciseMatch p1 e1 && preciseMatch p2 e2
_ -> False
PExt pext -> absurd pext
| |
9c638fbc459fdfe04f7d1387502bbbd7daa34638feb516c20fbb12d3416cdfae | weavejester/build | tasks.clj | (ns weavejester.build.tasks
(:refer-clojure :exclude [test])
(:require [babashka.fs :as fs]
[babashka.pods :as pods]
[babashka.tasks :as bb]
[weavejester.build.project :as p]))
(defn- run-clojure [deps ns args]
(apply bb/clojure "-Sdeps" (pr-str {:deps deps}) "-M" "-m" (str ns) args))
(defn clean
"Remove the target folder"
[]
(fs/delete-tree (:target-dir @p/project)))
(defn jar
"Create a jar file from the project"
[]
(bb/clojure "-Tbuild" "jar"))
(defn lint
"Lint the source files"
[]
(pods/load-pod "clj-kondo")
(require 'pod.borkdude.clj-kondo)
(let [lint-fn (resolve 'pod.borkdude.clj-kondo/run!)
print-fn (resolve 'pod.borkdude.clj-kondo/print!)
results (let [src (:src-dirs @p/project)]
(-> (lint-fn {:lint src})
(doto print-fn)))]
(when (-> results :findings seq)
(throw (ex-info "Lint warnings found, exiting with status code 1"
{:babashka/exit 1})))))
(defn outdated
"Find outdated dependencies"
[& args]
(run-clojure '{com.github.liquidz/antq {:mvn/version "1.3.1"}}
'antq.core args))
(defn repl
"Start a REPL for the project"
[& args]
(run-clojure '{com.bhauman/rebel-readline {:mvn/version "0.1.4"}}
'rebel-readline.main args))
(defn test
"Run tests for the project"
[& args]
(run-clojure '{lambdaisland/kaocha {:mvn/version "1.60.945"}}
'kaocha.runner args))
(defn uberjar
"Create an uberjar with the project and dependencies"
[]
(bb/clojure "-Tbuild" "uberjar"))
(defn deploy
"Deploy an uberjar to Clojars"
[]
(bb/clojure "-Tbuild" "deploy"))
| null | https://raw.githubusercontent.com/weavejester/build/8974b24113e4a4a9fa10656d14f61d8cb05a7392/src/weavejester/build/tasks.clj | clojure | (ns weavejester.build.tasks
(:refer-clojure :exclude [test])
(:require [babashka.fs :as fs]
[babashka.pods :as pods]
[babashka.tasks :as bb]
[weavejester.build.project :as p]))
(defn- run-clojure [deps ns args]
(apply bb/clojure "-Sdeps" (pr-str {:deps deps}) "-M" "-m" (str ns) args))
(defn clean
"Remove the target folder"
[]
(fs/delete-tree (:target-dir @p/project)))
(defn jar
"Create a jar file from the project"
[]
(bb/clojure "-Tbuild" "jar"))
(defn lint
"Lint the source files"
[]
(pods/load-pod "clj-kondo")
(require 'pod.borkdude.clj-kondo)
(let [lint-fn (resolve 'pod.borkdude.clj-kondo/run!)
print-fn (resolve 'pod.borkdude.clj-kondo/print!)
results (let [src (:src-dirs @p/project)]
(-> (lint-fn {:lint src})
(doto print-fn)))]
(when (-> results :findings seq)
(throw (ex-info "Lint warnings found, exiting with status code 1"
{:babashka/exit 1})))))
(defn outdated
"Find outdated dependencies"
[& args]
(run-clojure '{com.github.liquidz/antq {:mvn/version "1.3.1"}}
'antq.core args))
(defn repl
"Start a REPL for the project"
[& args]
(run-clojure '{com.bhauman/rebel-readline {:mvn/version "0.1.4"}}
'rebel-readline.main args))
(defn test
"Run tests for the project"
[& args]
(run-clojure '{lambdaisland/kaocha {:mvn/version "1.60.945"}}
'kaocha.runner args))
(defn uberjar
"Create an uberjar with the project and dependencies"
[]
(bb/clojure "-Tbuild" "uberjar"))
(defn deploy
"Deploy an uberjar to Clojars"
[]
(bb/clojure "-Tbuild" "deploy"))
| |
42cc67731332a523bb2724ca376134e7514f9e26ceadba5fc3c3a1e4e2e30afc | diasbruno/language-js | Spec.hs | module Main where
import Control.Monad (when)
import System.Exit
import Test.Hspec
import Test.Hspec.Runner
import Test.Helpers
import Test.MemberExpression
import Test.AssignmentAndOperation
import Test.Variables
import Test.If
import Test.Try
import Test.Switch
import Test.Functions
import Test.Classes
import Test.Iteration
import Test.Exports
import Test.Imports
testExpressions :: Spec
testExpressions = describe "Parse literals:" $ do
it "this" $ do
shouldBe (testExpression "this")
"Right LThis"
it "undefined/null" $ do
shouldBe (testExpression "null")
"Right LNull"
it "booleans" $ do
shouldBe (testExpression "true")
"Right (LB True)"
shouldBe (testExpression "false")
"Right (LB False)"
it "ident" $ do
shouldBe (testExpression "test")
"Right (LI \"test\")"
it "numbers" $ do
shouldBe (testExpression "1")
"Right (LN \"1\")"
shouldBe (testExpression "1.10")
"Right (LN \"1.10\")"
shouldBe (testExpression "0.10e3")
"Right (LN \"0.10e3\")"
shouldBe (testExpression "0x11")
"Right (LN \"0x11\")"
shouldBe (testExpression "0b11")
"Right (LN \"0b11\")"
it "strings" $ do
shouldBe (testExpression "\"test\"")
"Right (LS \"test\")"
shouldBe (testExpression "'test'")
"Right (LS \"test\")"
shouldBe (testExpression "'\\''")
"Right (LS \"'\")"
shouldBe (testExpression "'\\n'")
"Right (LS \"\\n\")"
shouldBe (testExpression "'\n'")
"Left \"dummy.js\" (line 1, column 2):\nunexpected \"\\n\"\nexpecting \"\\\\\" or \"'\""
it "template string" $ do
shouldBe (testExpression "`test`")
"Right (LTS [TString \"test\"])"
shouldBe (testExpression "`${\"a\"}`")
"Right (LTS [TExpression (LS \"a\")])"
shouldBe (testExpression "`test ${a + 1} test`")
"Right (LTS [TString \"test \",TExpression (Operation \"+\" (LI \"a\") (LN \"1\")),TString \" test\"])"
shouldBe (testExpression "`${a} test ${b}`")
"Right (LTS [TExpression (LI \"a\"),TString \" test \",TExpression (LI \"b\")])"
it "arrays" $ do
shouldBe (testExpression "[]")
"Right (LA [])"
shouldBe (testExpression "[,]")
"Right (LA [Elision])"
shouldBe (testExpression "[1,2]")
"Right (LA [LN \"1\",LN \"2\"])"
shouldBe (testExpression "[a,2]")
"Right (LA [LI \"a\",LN \"2\"])"
shouldBe (testExpression "[a,...b]")
"Right (LA [LI \"a\",Spread (LI \"b\")])"
shouldBe (testExpression "[a,...[1, 2]]")
"Right (LA [LI \"a\",Spread (LA [LN \"1\",LN \"2\"])])"
shouldBe (testExpression "[a,,b]")
"Right (LA [LI \"a\",Elision,LI \"b\"])"
it "objects" $ do
shouldBe (testExpression "{}")
"Right (LO [])"
shouldBe (testExpression "{a:1}")
"Right (LO [OPKV (LI \"a\") (LN \"1\")])"
shouldBe (testExpression "{b:2,c: \"d\"}")
"Right (LO [OPKV (LI \"b\") (LN \"2\"),OPKV (LI \"c\") (LS \"d\")])"
shouldBe (testExpression "{b:2, c:function() {}}")
"Right (LO [OPKV (LI \"b\") (LN \"2\"),OPKV (LI \"c\") (Function Nothing [] (SBlock []))])"
shouldBe (testExpression "{e}")
"Right (LO [OPI (LI \"e\")])"
shouldBe (testExpression "{e,f:1}")
"Right (LO [OPI (LI \"e\"),OPKV (LI \"f\") (LN \"1\")])"
shouldBe (testExpression "{e,...f}")
"Right (LO [OPI (LI \"e\"),OPI (Spread (LI \"f\"))])"
shouldBe (testExpression "{e,...{a:1}}")
"Right (LO [OPI (LI \"e\"),OPI (Spread (LO [OPKV (LI \"a\") (LN \"1\")]))])"
shouldBe (testExpression "{e,i:...{a:1}}")
"Right (LO [OPI (LI \"e\"),OPKV (LI \"i\") (Spread (LO [OPKV (LI \"a\") (LN \"1\")]))])"
shouldBe (testExpression "{e(){}}")
"Right (LO [OPM (PropertyMethod (LI \"e\") [] (SBlock []))])"
shouldBe (testExpression "{get e(){}}")
"Right (LO [OPM (ClassGetMethod (PropertyMethod (LI \"e\") [] (SBlock [])))])"
shouldBe (testExpression "{set e(){}}")
"Right (LO [OPM (ClassSetMethod (PropertyMethod (LI \"e\") [] (SBlock [])))])"
shouldBe (testExpression "{async e(){}}")
"Right (LO [OPM (Async (PropertyMethod (LI \"e\") [] (SBlock [])))])"
it "regular expression" $ do
shouldBe (testExpression "/test\\/asdf/")
"Right (RegExp \"test\\\\/asdf\" \"\")"
shouldBe (testExpression "/test\\/asdf/gmi")
"Right (RegExp \"test\\\\/asdf\" \"gmi\")"
shouldBe (testExpression "/test\\/asdf/gmi.exec(test)")
"Right (FCall (Dot (RegExp \"test\\\\/asdf\" \"gmi\") (LI \"exec\")) [LI \"test\"])"
it "parens expression" $ do
shouldBe (testExpression "(a,b)")
"Right (LP (Comma (LI \"a\") (LI \"b\")))"
it "new expression" $ testNewExpression
it "function call expression" $ testFunctionCall
it "dotted accesor" $ testDotAccessor
it "array accessor" $ testArrayAccessor
it "function expression" $ testFunctions
it "class expression" $ testClasses
it "unary expression" $ testUnaryOperations
it "assignment expression" $ testAssignments
it "operation expressions" $ testOperations
it "spread expression" $ do
shouldBe (testExpression "{...a}")
"Right (LO [OPI (Spread (LI \"a\"))])"
it "empty expression" $ do
shouldBe (testExpression ";")
"Right Empty"
testStatements = describe "Statements" $ do
it "empty statement" $ do
shouldBe (testStatement ";")
"Right (SExp Empty)"
it "if statement" $ testIf
it "try statement" $ testTry
it "throw statements" $ do
shouldBe (testStatement "throw x;")
"Right (SThrow (LI \"x\"))"
it "variable statements" $ testVariables
it "switch statement" $ testSwitch
it "continue statement" $ do
shouldBe (testStatement "continue")
"Right (SContinue Nothing)"
shouldBe (testStatement "continue x")
"Right (SContinue (Just (LI \"x\")))"
it "debugger statement" $ do
shouldBe (testStatement "debugger")
"Right SDebugger"
it "iteration statement" $ testIteration
it "with statement" $ do
shouldBe (testStatement "with (a) {}")
"Right (SWith (LI \"a\") (SBlock []))"
it "labelled statement" $ do
shouldBe (testStatement "a: x = 1")
"Right (SLabel (LI \"a\") (SExp (Assignment \"=\" (LI \"x\") (LN \"1\"))))"
it "import statement" $ testImports
it "export statement" $ testExports
it "function declaration" $ testFunctionDeclaration
it "class declaration" $ testClassesDeclaration
testAll :: Spec
testAll = do
testExpressions
testStatements
main :: IO ()
main = do
summary <- hspecWithResult defaultConfig testAll
when (summaryFailures summary == 0)
exitSuccess
exitFailure
| null | https://raw.githubusercontent.com/diasbruno/language-js/c986bb904e717fa8dd84f52473440ea726a275be/t/Spec.hs | haskell | module Main where
import Control.Monad (when)
import System.Exit
import Test.Hspec
import Test.Hspec.Runner
import Test.Helpers
import Test.MemberExpression
import Test.AssignmentAndOperation
import Test.Variables
import Test.If
import Test.Try
import Test.Switch
import Test.Functions
import Test.Classes
import Test.Iteration
import Test.Exports
import Test.Imports
testExpressions :: Spec
testExpressions = describe "Parse literals:" $ do
it "this" $ do
shouldBe (testExpression "this")
"Right LThis"
it "undefined/null" $ do
shouldBe (testExpression "null")
"Right LNull"
it "booleans" $ do
shouldBe (testExpression "true")
"Right (LB True)"
shouldBe (testExpression "false")
"Right (LB False)"
it "ident" $ do
shouldBe (testExpression "test")
"Right (LI \"test\")"
it "numbers" $ do
shouldBe (testExpression "1")
"Right (LN \"1\")"
shouldBe (testExpression "1.10")
"Right (LN \"1.10\")"
shouldBe (testExpression "0.10e3")
"Right (LN \"0.10e3\")"
shouldBe (testExpression "0x11")
"Right (LN \"0x11\")"
shouldBe (testExpression "0b11")
"Right (LN \"0b11\")"
it "strings" $ do
shouldBe (testExpression "\"test\"")
"Right (LS \"test\")"
shouldBe (testExpression "'test'")
"Right (LS \"test\")"
shouldBe (testExpression "'\\''")
"Right (LS \"'\")"
shouldBe (testExpression "'\\n'")
"Right (LS \"\\n\")"
shouldBe (testExpression "'\n'")
"Left \"dummy.js\" (line 1, column 2):\nunexpected \"\\n\"\nexpecting \"\\\\\" or \"'\""
it "template string" $ do
shouldBe (testExpression "`test`")
"Right (LTS [TString \"test\"])"
shouldBe (testExpression "`${\"a\"}`")
"Right (LTS [TExpression (LS \"a\")])"
shouldBe (testExpression "`test ${a + 1} test`")
"Right (LTS [TString \"test \",TExpression (Operation \"+\" (LI \"a\") (LN \"1\")),TString \" test\"])"
shouldBe (testExpression "`${a} test ${b}`")
"Right (LTS [TExpression (LI \"a\"),TString \" test \",TExpression (LI \"b\")])"
it "arrays" $ do
shouldBe (testExpression "[]")
"Right (LA [])"
shouldBe (testExpression "[,]")
"Right (LA [Elision])"
shouldBe (testExpression "[1,2]")
"Right (LA [LN \"1\",LN \"2\"])"
shouldBe (testExpression "[a,2]")
"Right (LA [LI \"a\",LN \"2\"])"
shouldBe (testExpression "[a,...b]")
"Right (LA [LI \"a\",Spread (LI \"b\")])"
shouldBe (testExpression "[a,...[1, 2]]")
"Right (LA [LI \"a\",Spread (LA [LN \"1\",LN \"2\"])])"
shouldBe (testExpression "[a,,b]")
"Right (LA [LI \"a\",Elision,LI \"b\"])"
it "objects" $ do
shouldBe (testExpression "{}")
"Right (LO [])"
shouldBe (testExpression "{a:1}")
"Right (LO [OPKV (LI \"a\") (LN \"1\")])"
shouldBe (testExpression "{b:2,c: \"d\"}")
"Right (LO [OPKV (LI \"b\") (LN \"2\"),OPKV (LI \"c\") (LS \"d\")])"
shouldBe (testExpression "{b:2, c:function() {}}")
"Right (LO [OPKV (LI \"b\") (LN \"2\"),OPKV (LI \"c\") (Function Nothing [] (SBlock []))])"
shouldBe (testExpression "{e}")
"Right (LO [OPI (LI \"e\")])"
shouldBe (testExpression "{e,f:1}")
"Right (LO [OPI (LI \"e\"),OPKV (LI \"f\") (LN \"1\")])"
shouldBe (testExpression "{e,...f}")
"Right (LO [OPI (LI \"e\"),OPI (Spread (LI \"f\"))])"
shouldBe (testExpression "{e,...{a:1}}")
"Right (LO [OPI (LI \"e\"),OPI (Spread (LO [OPKV (LI \"a\") (LN \"1\")]))])"
shouldBe (testExpression "{e,i:...{a:1}}")
"Right (LO [OPI (LI \"e\"),OPKV (LI \"i\") (Spread (LO [OPKV (LI \"a\") (LN \"1\")]))])"
shouldBe (testExpression "{e(){}}")
"Right (LO [OPM (PropertyMethod (LI \"e\") [] (SBlock []))])"
shouldBe (testExpression "{get e(){}}")
"Right (LO [OPM (ClassGetMethod (PropertyMethod (LI \"e\") [] (SBlock [])))])"
shouldBe (testExpression "{set e(){}}")
"Right (LO [OPM (ClassSetMethod (PropertyMethod (LI \"e\") [] (SBlock [])))])"
shouldBe (testExpression "{async e(){}}")
"Right (LO [OPM (Async (PropertyMethod (LI \"e\") [] (SBlock [])))])"
it "regular expression" $ do
shouldBe (testExpression "/test\\/asdf/")
"Right (RegExp \"test\\\\/asdf\" \"\")"
shouldBe (testExpression "/test\\/asdf/gmi")
"Right (RegExp \"test\\\\/asdf\" \"gmi\")"
shouldBe (testExpression "/test\\/asdf/gmi.exec(test)")
"Right (FCall (Dot (RegExp \"test\\\\/asdf\" \"gmi\") (LI \"exec\")) [LI \"test\"])"
it "parens expression" $ do
shouldBe (testExpression "(a,b)")
"Right (LP (Comma (LI \"a\") (LI \"b\")))"
it "new expression" $ testNewExpression
it "function call expression" $ testFunctionCall
it "dotted accesor" $ testDotAccessor
it "array accessor" $ testArrayAccessor
it "function expression" $ testFunctions
it "class expression" $ testClasses
it "unary expression" $ testUnaryOperations
it "assignment expression" $ testAssignments
it "operation expressions" $ testOperations
it "spread expression" $ do
shouldBe (testExpression "{...a}")
"Right (LO [OPI (Spread (LI \"a\"))])"
it "empty expression" $ do
shouldBe (testExpression ";")
"Right Empty"
testStatements = describe "Statements" $ do
it "empty statement" $ do
shouldBe (testStatement ";")
"Right (SExp Empty)"
it "if statement" $ testIf
it "try statement" $ testTry
it "throw statements" $ do
shouldBe (testStatement "throw x;")
"Right (SThrow (LI \"x\"))"
it "variable statements" $ testVariables
it "switch statement" $ testSwitch
it "continue statement" $ do
shouldBe (testStatement "continue")
"Right (SContinue Nothing)"
shouldBe (testStatement "continue x")
"Right (SContinue (Just (LI \"x\")))"
it "debugger statement" $ do
shouldBe (testStatement "debugger")
"Right SDebugger"
it "iteration statement" $ testIteration
it "with statement" $ do
shouldBe (testStatement "with (a) {}")
"Right (SWith (LI \"a\") (SBlock []))"
it "labelled statement" $ do
shouldBe (testStatement "a: x = 1")
"Right (SLabel (LI \"a\") (SExp (Assignment \"=\" (LI \"x\") (LN \"1\"))))"
it "import statement" $ testImports
it "export statement" $ testExports
it "function declaration" $ testFunctionDeclaration
it "class declaration" $ testClassesDeclaration
testAll :: Spec
testAll = do
testExpressions
testStatements
main :: IO ()
main = do
summary <- hspecWithResult defaultConfig testAll
when (summaryFailures summary == 0)
exitSuccess
exitFailure
| |
5bfb37b05c3fda1f768e12352d6fca15c95a925d0cf094164076d972cf83fd54 | dcavar/schemeNLP | countbigrams1.scm | ":"; exec mzscheme -r $0 "$@"
;;; ----------------------------------------------------
;;; Filename: countbigrams1.ss
Author : < >
;;;
( C ) 2006 by
;;;
;;; This code is published under the restrictive GPL!
;;; Please find the text of the GPL here:
;;;
;;;
;;; It is free for use, change, etc. as long as the copyright
;;; note above is included in any modified version of the code.
;;;
;;; This script assumes that the text is raw and encoded in UTF8.
;;;
;;; Functions:
1 . The text file is loaded into memory .
2 . The text is tokenized , i.e. converted into a list of tokens .
3 . Two adjacent tokens are placed into a hash - table as keys , the value
;;; is the absolute frequency (i.e. count) of each token in the
;;; text.
4 . The hash - table is converted into a list of key - value tuples .
5 . The key - values are sorted by value , and a list of bigrams
;;; and their frequency is printed out.
;;;
If the command line parameters contain more than one text file ,
;;; the above results are accumulated over all the input text files.
;;;
;;; Usage:
;;; mzscheme -r countbigrams1.ss test1.txt test2.txt ...
;;; ----------------------------------------------------
;;; all necessary libraries and functions
(require (lib "list.ss"))
(require (lib "string.ss" "srfi" "13"))
(require (lib "vector-lib.ss" "srfi" "43"))
;;; Global variables
(define bigramcount 0.0) ; total number of bigrams
(define bigrams (make-hash-table 'equal)) ; hash-table container for bigram-count pairs
;;; print-wordlist
;;; <- hash-table of key-value pairs
;;; side effect: print out of tab-delimited key-value pairs per line
;;; ----------------------------------------------------
;;; Pretty print wordlist as tab-delimited key-value lines.
(define print-bigramlist!
(lambda (table)
(hash-table-for-each table
(lambda (key value)
(printf "~a ~a\t~a\n" (car key) (cadr key) value)))))
;;; sort-by-value
;;; <- hash-table
;;; -> list of key-value tuples (lists)
;;; ----------------------------------------------------
;;; Sort a hash-table of key-value pairs by value, by converting it
;;; into a list of key-value tuples and sorting on the value.
(define sort-by-value
(lambda (table)
(let ([keyval (hash-table-map table (lambda (key val) (list key val)))])
(sort keyval (lambda (a b)
(< (cadr a) (cadr b)))))))
;;; add-bigrams
;;; <- list of strings, i.e. token list
;;; !-> updated hash-table bigram-hash
;;; !-> updated count-bigrams counter
;;; ----------------------------------------------------
;;; Add word-bigrams from an ordered list of tokens to the hash-table
;;; container and keep track of their count.
(define add-bigrams
(lambda (words)
(let ([count (- (length words) 1)]) ; how many bigrams
(set! bigramcount (+ bigramcount count)) ; remember the total count
(let loop ([i 1])
(let* ([bigram (list (list-ref words (- i 1)) (list-ref words i))] ; create bigram
[value (hash-table-get bigrams bigram 0.0)]) ; get the calue for bigram
(hash-table-put! bigrams bigram (+ value 1)))
(if (< i count)
(loop (+ i 1)))))))
;;; load-file
;;; <- string filename
;;; -> string file content
;;; ----------------------------------------------------
;;; Load text from file into a string variable and return it.
(define load-file
(lambda (name)
(call-with-input-file name
(lambda (p)
(read-string (file-size name) p)))))
;;; main steps
(begin
(vector-for-each (lambda (i fname)
(printf "Loading file: ~a\n" fname)
(add-bigrams (string-tokenize (load-file fname))))
argv)
(printf "Number of tokens: ~a\n" bigramcount)
(printf "Number of types: ~a\n" (hash-table-count bigrams))
(printf "---------------------------------------------------------\n")
;(print-bigramlist! bigrams)
(let ([result (sort-by-value bigrams)])
(printf "Decreasing frequency profile:\n")
(for-each (lambda (a)
(let ([bigram (car a)])
(printf "~a ~a\t~a\n" (car bigram) (cadr bigram) (cadr a))))
(reverse result))))
| null | https://raw.githubusercontent.com/dcavar/schemeNLP/daa0ddcc4fa67fe00dcf6054c4d30d11a00b2f7f/src/countbigrams1.scm | scheme | exec mzscheme -r $0 "$@"
----------------------------------------------------
Filename: countbigrams1.ss
This code is published under the restrictive GPL!
Please find the text of the GPL here:
It is free for use, change, etc. as long as the copyright
note above is included in any modified version of the code.
This script assumes that the text is raw and encoded in UTF8.
Functions:
is the absolute frequency (i.e. count) of each token in the
text.
and their frequency is printed out.
the above results are accumulated over all the input text files.
Usage:
mzscheme -r countbigrams1.ss test1.txt test2.txt ...
----------------------------------------------------
all necessary libraries and functions
Global variables
total number of bigrams
hash-table container for bigram-count pairs
print-wordlist
<- hash-table of key-value pairs
side effect: print out of tab-delimited key-value pairs per line
----------------------------------------------------
Pretty print wordlist as tab-delimited key-value lines.
sort-by-value
<- hash-table
-> list of key-value tuples (lists)
----------------------------------------------------
Sort a hash-table of key-value pairs by value, by converting it
into a list of key-value tuples and sorting on the value.
add-bigrams
<- list of strings, i.e. token list
!-> updated hash-table bigram-hash
!-> updated count-bigrams counter
----------------------------------------------------
Add word-bigrams from an ordered list of tokens to the hash-table
container and keep track of their count.
how many bigrams
remember the total count
create bigram
get the calue for bigram
load-file
<- string filename
-> string file content
----------------------------------------------------
Load text from file into a string variable and return it.
main steps
(print-bigramlist! bigrams) |
Author : < >
( C ) 2006 by
1 . The text file is loaded into memory .
2 . The text is tokenized , i.e. converted into a list of tokens .
3 . Two adjacent tokens are placed into a hash - table as keys , the value
4 . The hash - table is converted into a list of key - value tuples .
5 . The key - values are sorted by value , and a list of bigrams
If the command line parameters contain more than one text file ,
(require (lib "list.ss"))
(require (lib "string.ss" "srfi" "13"))
(require (lib "vector-lib.ss" "srfi" "43"))
(define print-bigramlist!
(lambda (table)
(hash-table-for-each table
(lambda (key value)
(printf "~a ~a\t~a\n" (car key) (cadr key) value)))))
(define sort-by-value
(lambda (table)
(let ([keyval (hash-table-map table (lambda (key val) (list key val)))])
(sort keyval (lambda (a b)
(< (cadr a) (cadr b)))))))
(define add-bigrams
(lambda (words)
(let loop ([i 1])
(hash-table-put! bigrams bigram (+ value 1)))
(if (< i count)
(loop (+ i 1)))))))
(define load-file
(lambda (name)
(call-with-input-file name
(lambda (p)
(read-string (file-size name) p)))))
(begin
(vector-for-each (lambda (i fname)
(printf "Loading file: ~a\n" fname)
(add-bigrams (string-tokenize (load-file fname))))
argv)
(printf "Number of tokens: ~a\n" bigramcount)
(printf "Number of types: ~a\n" (hash-table-count bigrams))
(printf "---------------------------------------------------------\n")
(let ([result (sort-by-value bigrams)])
(printf "Decreasing frequency profile:\n")
(for-each (lambda (a)
(let ([bigram (car a)])
(printf "~a ~a\t~a\n" (car bigram) (cadr bigram) (cadr a))))
(reverse result))))
|
b96e69a24dcdb6ec6734ba5387da18999957cd26794158853fa943197fcf1a84 | semilin/layoup | Rspace_Rollin.lisp |
(MAKE-LAYOUT :NAME "Rspace_Rollin" :MATRIX (APPLY #'KEY-MATRIX 'NIL)
:SHIFT-MATRIX NIL :KEYBOARD NIL) | null | https://raw.githubusercontent.com/semilin/layoup/27ec9ba9a9388cd944ac46206d10424e3ab45499/data/layouts/Rspace_Rollin.lisp | lisp |
(MAKE-LAYOUT :NAME "Rspace_Rollin" :MATRIX (APPLY #'KEY-MATRIX 'NIL)
:SHIFT-MATRIX NIL :KEYBOARD NIL) | |
2348c89c5ccabab9237c87a6e55cf0a82bfccdab87a5f43c5ac1b0d3955556b4 | mhuebert/maria | live_layout.cljs | (ns maria.pages.live-layout
(:require [chia.view :as v]
[maria.views.floating.tooltip :as tooltip]
[chia.db :as d]
[maria.commands.which-key :as which-key]
[maria.repl-specials]
[cljs.core.match :refer-macros [match]]
[maria.views.floating.float-ui :as hint]
[maria.views.bottom-bar :as dock]
[maria.pages.docs :as docs]
[maria.views.top-bar :as toolbar]
[lark.commands.exec :as exec]
[maria.commands.doc :as doc]
[maria.views.icons :as icons]
[bidi.bidi :as bidi]
[clojure.string :as str]
[maria.util :as util]
[chia.view.props :as props]))
(defonce _
(d/transact! [[:db/add :ui/globals :sidebar-width 250]
#_[:db/add :remote/status :in-progress true]]))
(defn last-n [n v]
(subvec v (max 0 (- (count v) n))))
(defn link [title href]
[:a (cond-> {:href href}
(str/starts-with? title "http")
(assoc :target "_blank")) title])
(defn landing []
[:.w-100
[toolbar/doc-toolbar {}]
[:.h2]
[:.tc.serif.center.ph3
{:style {:max-width 600}}
[:.f1.mb3.pt5 "Welcome to Maria,"]
[:.f3.mv3 "a coding environment for beginners."]
[:.flex.items-center.f3.mv4.br3.bg-darken.pa3
[:.flex-auto]
"Your journey begins here: "
[:a.br2.bg-white.shadow-4.pa3.ml3.sans-serif.black.no-underline.f5.b.pointer.hover-underline.hover-shadow-5 {:href "/intro"} "Learn Clojure with Shapes"]
[:.flex-auto]]
[:.tc.i.f3.mv3 "Further reading:"]
[:ul.f-body.tl.lh-copy
[:li "An " (link "Example Gallery" "/gallery?eval=true") " of user creations."]
[:li "The " (link "Editor Quickstart" "/quickstart") " explains how to use Maria."]
[:li "Understand the " (link "Pedagogy" "") " behind Maria's curriculum."]
[:li "Discover " (link "Sources of Inspiration" "-reading") " for the project."]]]])
(v/defview sidebar
[{:keys [visible? id]}]
(let [width (d/get :ui/globals :sidebar-width)]
[:.fixed.f7.z-5.top-0.bottom-0.flex.flex-column.bg-white.b--moon-gray.bw1.br
{:style {:width width
:transition "all ease 0.2s"
:left (if visible? 0 (- width))}}
[:.flex.items-stretch.pl1.flex-none.bg-darken-lightly
#_(toolbar/toolbar-button [{:on-click #(d/transact! [[:db/add :ui/globals :sidebar? nil]])}
icons/Docs
nil
"Docs"])
#_(toolbar/toolbar-button [{:on-click #(exec/exec-command-name :doc/new)}
nil
"New"
"New Doc"])
(toolbar/toolbar-button [{:href "/"}
icons/Home
nil
"Home"])
[:.flex-auto]
(toolbar/toolbar-button [{:on-click #(d/transact! [[:db/add :ui/globals :sidebar? nil]])}
(-> icons/ExpandMore
(icons/style {:transform "rotate(90deg)"})
(icons/class "o-60"))
nil
"Close"])]
[:.overflow-y-auto.bg-white.pb4
(some->> (doc/locals-docs :local/recents)
(docs/doc-list {:context :recents
:id id
:title "Recent"}))
(some->> doc/curriculum
(docs/doc-list {:context :curriculum
:id id
:title "Learning Modules"
:limit 0}))
(when-let [username (d/get :auth-public :username)]
(some->> (seq (doc/user-gists username))
(docs/doc-list {:context :gists
:id id
:title (str username "'s Gists")
:limit 0})))
(some->> (doc/locals-docs :local/trash)
(docs/doc-list {:context :trash
:id id
:title "Trash"
:limit 0}))]]))
(def routes ["/" {"" landing
"home" landing
["doc/" [#".*" :id]] docs/file-edit
["gists/" [#".*" :username]] docs/gists-list
["local/" [#".*" :id]] (props/partial docs/file-edit {:local? true})
"local" (props/partial docs/gists-list {:username "local"})}])
(v/defclass remote-progress []
(let [active? (> (d/get :remote/status :in-progress) 0)]
[:div {:style {:height (if active? 10 0)
:left 0
:right 0
:top 0
:position "absolute"}}
(when active?
[:.progress-indeterminate])]))
(v/defclass layout
[{:keys []}]
(let [sidebar? (d/get :ui/globals :sidebar?)
path (str "/" (str/join "/" (d/get :router/location :segments)))
{:keys [route-params handler]} (when (d/contains? :router/location)
(-> (bidi/match-route routes path)
;; normalize encoding... bidi leaves route params in a partially decoded state
(update :route-params
(partial util/map-vals
(comp js/encodeURIComponent js/decodeURIComponent)))))]
[:.w-100.relative.sans-serif.cursor-text
{:on-click #(when (= (.-target %) (.-currentTarget %))
(exec/exec-command-name :navigate/focus-end))
:style {:min-height "100%"
:padding-bottom 140
:transition "padding-left ease 0.2s"
:padding-left (when sidebar? (d/get :ui/globals :sidebar-width))}}
[remote-progress]
[hint/show-floating-view]
[sidebar {:visible? sidebar?
:id (:id route-params)}]
[:.relative.w-100
(when handler
(handler route-params))]
[which-key/show-commands]
[dock/BottomBar {}]
[tooltip/Tooltip]]))
| null | https://raw.githubusercontent.com/mhuebert/maria/15586564796bc9273ace3101b21662d0c66b4d22/editor/src/maria/pages/live_layout.cljs | clojure | normalize encoding... bidi leaves route params in a partially decoded state | (ns maria.pages.live-layout
(:require [chia.view :as v]
[maria.views.floating.tooltip :as tooltip]
[chia.db :as d]
[maria.commands.which-key :as which-key]
[maria.repl-specials]
[cljs.core.match :refer-macros [match]]
[maria.views.floating.float-ui :as hint]
[maria.views.bottom-bar :as dock]
[maria.pages.docs :as docs]
[maria.views.top-bar :as toolbar]
[lark.commands.exec :as exec]
[maria.commands.doc :as doc]
[maria.views.icons :as icons]
[bidi.bidi :as bidi]
[clojure.string :as str]
[maria.util :as util]
[chia.view.props :as props]))
(defonce _
(d/transact! [[:db/add :ui/globals :sidebar-width 250]
#_[:db/add :remote/status :in-progress true]]))
(defn last-n [n v]
(subvec v (max 0 (- (count v) n))))
(defn link [title href]
[:a (cond-> {:href href}
(str/starts-with? title "http")
(assoc :target "_blank")) title])
(defn landing []
[:.w-100
[toolbar/doc-toolbar {}]
[:.h2]
[:.tc.serif.center.ph3
{:style {:max-width 600}}
[:.f1.mb3.pt5 "Welcome to Maria,"]
[:.f3.mv3 "a coding environment for beginners."]
[:.flex.items-center.f3.mv4.br3.bg-darken.pa3
[:.flex-auto]
"Your journey begins here: "
[:a.br2.bg-white.shadow-4.pa3.ml3.sans-serif.black.no-underline.f5.b.pointer.hover-underline.hover-shadow-5 {:href "/intro"} "Learn Clojure with Shapes"]
[:.flex-auto]]
[:.tc.i.f3.mv3 "Further reading:"]
[:ul.f-body.tl.lh-copy
[:li "An " (link "Example Gallery" "/gallery?eval=true") " of user creations."]
[:li "The " (link "Editor Quickstart" "/quickstart") " explains how to use Maria."]
[:li "Understand the " (link "Pedagogy" "") " behind Maria's curriculum."]
[:li "Discover " (link "Sources of Inspiration" "-reading") " for the project."]]]])
(v/defview sidebar
[{:keys [visible? id]}]
(let [width (d/get :ui/globals :sidebar-width)]
[:.fixed.f7.z-5.top-0.bottom-0.flex.flex-column.bg-white.b--moon-gray.bw1.br
{:style {:width width
:transition "all ease 0.2s"
:left (if visible? 0 (- width))}}
[:.flex.items-stretch.pl1.flex-none.bg-darken-lightly
#_(toolbar/toolbar-button [{:on-click #(d/transact! [[:db/add :ui/globals :sidebar? nil]])}
icons/Docs
nil
"Docs"])
#_(toolbar/toolbar-button [{:on-click #(exec/exec-command-name :doc/new)}
nil
"New"
"New Doc"])
(toolbar/toolbar-button [{:href "/"}
icons/Home
nil
"Home"])
[:.flex-auto]
(toolbar/toolbar-button [{:on-click #(d/transact! [[:db/add :ui/globals :sidebar? nil]])}
(-> icons/ExpandMore
(icons/style {:transform "rotate(90deg)"})
(icons/class "o-60"))
nil
"Close"])]
[:.overflow-y-auto.bg-white.pb4
(some->> (doc/locals-docs :local/recents)
(docs/doc-list {:context :recents
:id id
:title "Recent"}))
(some->> doc/curriculum
(docs/doc-list {:context :curriculum
:id id
:title "Learning Modules"
:limit 0}))
(when-let [username (d/get :auth-public :username)]
(some->> (seq (doc/user-gists username))
(docs/doc-list {:context :gists
:id id
:title (str username "'s Gists")
:limit 0})))
(some->> (doc/locals-docs :local/trash)
(docs/doc-list {:context :trash
:id id
:title "Trash"
:limit 0}))]]))
(def routes ["/" {"" landing
"home" landing
["doc/" [#".*" :id]] docs/file-edit
["gists/" [#".*" :username]] docs/gists-list
["local/" [#".*" :id]] (props/partial docs/file-edit {:local? true})
"local" (props/partial docs/gists-list {:username "local"})}])
(v/defclass remote-progress []
(let [active? (> (d/get :remote/status :in-progress) 0)]
[:div {:style {:height (if active? 10 0)
:left 0
:right 0
:top 0
:position "absolute"}}
(when active?
[:.progress-indeterminate])]))
(v/defclass layout
[{:keys []}]
(let [sidebar? (d/get :ui/globals :sidebar?)
path (str "/" (str/join "/" (d/get :router/location :segments)))
{:keys [route-params handler]} (when (d/contains? :router/location)
(-> (bidi/match-route routes path)
(update :route-params
(partial util/map-vals
(comp js/encodeURIComponent js/decodeURIComponent)))))]
[:.w-100.relative.sans-serif.cursor-text
{:on-click #(when (= (.-target %) (.-currentTarget %))
(exec/exec-command-name :navigate/focus-end))
:style {:min-height "100%"
:padding-bottom 140
:transition "padding-left ease 0.2s"
:padding-left (when sidebar? (d/get :ui/globals :sidebar-width))}}
[remote-progress]
[hint/show-floating-view]
[sidebar {:visible? sidebar?
:id (:id route-params)}]
[:.relative.w-100
(when handler
(handler route-params))]
[which-key/show-commands]
[dock/BottomBar {}]
[tooltip/Tooltip]]))
|
ed2750de04aea1681375b3c8c30f5e074bac4b5c388cd53947a1573c7347de68 | csabahruska/jhc-components | CPUTime.hs | module CPUTime (
getCPUTime, cpuTimePrecision
) where
import System.CPUTime
| null | https://raw.githubusercontent.com/csabahruska/jhc-components/a7dace481d017f5a83fbfc062bdd2d099133adf1/lib/haskell98/CPUTime.hs | haskell | module CPUTime (
getCPUTime, cpuTimePrecision
) where
import System.CPUTime
| |
a0118ae38e4315377b24de1eaf1330dd2942bad354248cbcdbffe39d83044469 | camlspotter/ocaml-zippy-tutorial-in-japanese | w7.ml | class c = object
method m = print_endline "hello"
end
class c' = object
inherit c
< = Warning 7
end
Warning 7 : the method m is overridden .
| null | https://raw.githubusercontent.com/camlspotter/ocaml-zippy-tutorial-in-japanese/c6aeabc08b6e2289a0e66c5b94a89c6723d88a6a/t/warnings/w7.ml | ocaml | class c = object
method m = print_endline "hello"
end
class c' = object
inherit c
< = Warning 7
end
Warning 7 : the method m is overridden .
| |
2c19d3bfdaef404e4c5d431e18b2e8329df207856bc932c0dbd277df23ace2ba | cdfa/frugel | Event.hs | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE RecordWildCards #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
module Frugel.Web.Event where
import Data.Aeson.Types
import Frugel
import Frugel.Web.Action
import Miso ( Attribute, Options(..), defaultOptions, onWithOptions )
import Miso.Event.Decoder hiding ( keyInfoDecoder )
import Optics.Extra.Scout
data KeyInfo
= KeyInfo { key :: !String, shiftKey, metaKey, ctrlKey, altKey :: !Bool }
deriving ( Show, Eq )
makeFieldLabelsNoPrefix ''KeyInfo
keyDownHandler :: Attribute Action
keyDownHandler = onKeyDownWithInfo handleKeyDown
where
handleKeyDown keyInfo@KeyInfo{..}
= if noModifiers keyInfo
then (case key of
[c] -> GenericAction $ Insert c
"Enter" -> GenericAction $ Insert '\n'
"Tab" -> GenericAction $ Insert '\t'
"Delete" -> GenericAction Delete
"Backspace" -> GenericAction Backspace
"ArrowLeft" -> GenericAction $ Move Leftward
"ArrowRight" -> GenericAction $ Move Rightward
"ArrowUp" -> GenericAction $ Move Upward
"ArrowDown" -> GenericAction $ Move Downward
_ -> Log key)
else (case key of
[c] | singleModifier #shiftKey keyInfo ->
GenericAction $ Insert c
"Enter" | singleModifier #ctrlKey keyInfo -> PrettyPrint
Up and down also available with Alt to prevent window scrolling until is fixed
"ArrowUp" | singleModifier #altKey keyInfo ->
GenericAction $ Move Upward
"ArrowDown" | singleModifier #altKey keyInfo ->
GenericAction $ Move Downward
-- Left and right also allowed with Alt, because pressing/releasing Alt repeatedly while navigating is annoying
"ArrowLeft" | singleModifier #altKey keyInfo ->
GenericAction $ Move Leftward
"ArrowRight" | singleModifier #altKey keyInfo ->
GenericAction $ Move Rightward
_ -> Log key)
noModifiers :: KeyInfo -> Bool
noModifiers KeyInfo{..} = not $ metaKey || ctrlKey || altKey || shiftKey
singleModifier :: (Is k A_Setter, Is k A_Getter)
=> Optic k is KeyInfo KeyInfo Bool Bool
-> KeyInfo
-> Bool
singleModifier modifier keyInfo
= noModifiers (keyInfo & modifier .~ False) && view modifier keyInfo
-- | -US/docs/Web/Events/keydown
onKeyDownWithInfo :: (KeyInfo -> action) -> Attribute action
onKeyDownWithInfo
= onWithOptions (Miso.defaultOptions { preventDefault = False })
"keydown"
keyInfoDecoder
keyInfoDecoder :: Decoder KeyInfo
keyInfoDecoder = Decoder { .. }
where
decodeAt = DecodeTarget mempty
decoder = withObject "event" $ \o -> KeyInfo <$> o .: "key"
<*> o .: "shiftKey"
<*> o .: "metaKey"
<*> o .: "ctrlKey"
<*> o .: "altKey"
| null | https://raw.githubusercontent.com/cdfa/frugel/d412673d8925a6f9eaad4e043cbd8fa46ed50aa2/app/Frugel/Web/Event.hs | haskell | Left and right also allowed with Alt, because pressing/releasing Alt repeatedly while navigating is annoying
| -US/docs/Web/Events/keydown | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE RecordWildCards #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
module Frugel.Web.Event where
import Data.Aeson.Types
import Frugel
import Frugel.Web.Action
import Miso ( Attribute, Options(..), defaultOptions, onWithOptions )
import Miso.Event.Decoder hiding ( keyInfoDecoder )
import Optics.Extra.Scout
data KeyInfo
= KeyInfo { key :: !String, shiftKey, metaKey, ctrlKey, altKey :: !Bool }
deriving ( Show, Eq )
makeFieldLabelsNoPrefix ''KeyInfo
keyDownHandler :: Attribute Action
keyDownHandler = onKeyDownWithInfo handleKeyDown
where
handleKeyDown keyInfo@KeyInfo{..}
= if noModifiers keyInfo
then (case key of
[c] -> GenericAction $ Insert c
"Enter" -> GenericAction $ Insert '\n'
"Tab" -> GenericAction $ Insert '\t'
"Delete" -> GenericAction Delete
"Backspace" -> GenericAction Backspace
"ArrowLeft" -> GenericAction $ Move Leftward
"ArrowRight" -> GenericAction $ Move Rightward
"ArrowUp" -> GenericAction $ Move Upward
"ArrowDown" -> GenericAction $ Move Downward
_ -> Log key)
else (case key of
[c] | singleModifier #shiftKey keyInfo ->
GenericAction $ Insert c
"Enter" | singleModifier #ctrlKey keyInfo -> PrettyPrint
Up and down also available with Alt to prevent window scrolling until is fixed
"ArrowUp" | singleModifier #altKey keyInfo ->
GenericAction $ Move Upward
"ArrowDown" | singleModifier #altKey keyInfo ->
GenericAction $ Move Downward
"ArrowLeft" | singleModifier #altKey keyInfo ->
GenericAction $ Move Leftward
"ArrowRight" | singleModifier #altKey keyInfo ->
GenericAction $ Move Rightward
_ -> Log key)
noModifiers :: KeyInfo -> Bool
noModifiers KeyInfo{..} = not $ metaKey || ctrlKey || altKey || shiftKey
singleModifier :: (Is k A_Setter, Is k A_Getter)
=> Optic k is KeyInfo KeyInfo Bool Bool
-> KeyInfo
-> Bool
singleModifier modifier keyInfo
= noModifiers (keyInfo & modifier .~ False) && view modifier keyInfo
onKeyDownWithInfo :: (KeyInfo -> action) -> Attribute action
onKeyDownWithInfo
= onWithOptions (Miso.defaultOptions { preventDefault = False })
"keydown"
keyInfoDecoder
keyInfoDecoder :: Decoder KeyInfo
keyInfoDecoder = Decoder { .. }
where
decodeAt = DecodeTarget mempty
decoder = withObject "event" $ \o -> KeyInfo <$> o .: "key"
<*> o .: "shiftKey"
<*> o .: "metaKey"
<*> o .: "ctrlKey"
<*> o .: "altKey"
|
3e49a044b8ab9cdf3dee8b130b75725d1c143e86664a22f41d97b79ef4a15246 | malcolmreynolds/GSLL | error-functions.lisp | ;; Error functions
, Mon Mar 20 2006 - 22:31
Time - stamp : < 2008 - 10 - 23 22:50:45EDT error-functions.lisp >
$ Id$
(in-package :gsl)
(defmfun erf (x)
"gsl_sf_erf_e" ((x :double) (ret sf-result))
"The error function erf(x), where
erf(x) = (2/\sqrt(\pi)) \int_0^x dt \exp(-t^2).")
(defmfun erfc (x)
"gsl_sf_erfc_e" ((x :double) (ret sf-result))
"The complementary error function
erfc(x) = 1 - erf(x) = (2/\sqrt(\pi)) \int_x^\infty \exp(-t^2).")
(defmfun log-erfc (x)
"gsl_sf_log_erfc_e" ((x :double) (ret sf-result))
"The logarithm of the complementary error function \log(\erfc(x)).")
(defmfun erf-Z (x)
"gsl_sf_erf_Z_e" ((x :double) (ret sf-result))
"The Gaussian probability density function
Z(x) = (1/sqrt{2\pi}) \exp(-x^2/2)}.")
(defmfun erf-Q (x)
"gsl_sf_erf_Q_e" ((x :double) (ret sf-result))
"The upper tail of the Gaussian probability function
Q(x) = (1/\sqrt{2\pi}) \int_x^\infty dt \exp(-t^2/2)}.")
(defmfun hazard (x)
"gsl_sf_hazard_e" ((x :double) (ret sf-result))
"The hazard function for the normal distribution.")
(save-test error-functions
(erf 1.0d0)
(erfc 1.0d0)
(log-erfc 1.0d0)
(erf-z 1.0d0)
(erf-q 1.0d0)
(hazard 1.0d0))
| null | https://raw.githubusercontent.com/malcolmreynolds/GSLL/2f722f12f1d08e1b9550a46e2a22adba8e1e52c4/special-functions/error-functions.lisp | lisp | Error functions | , Mon Mar 20 2006 - 22:31
Time - stamp : < 2008 - 10 - 23 22:50:45EDT error-functions.lisp >
$ Id$
(in-package :gsl)
(defmfun erf (x)
"gsl_sf_erf_e" ((x :double) (ret sf-result))
"The error function erf(x), where
erf(x) = (2/\sqrt(\pi)) \int_0^x dt \exp(-t^2).")
(defmfun erfc (x)
"gsl_sf_erfc_e" ((x :double) (ret sf-result))
"The complementary error function
erfc(x) = 1 - erf(x) = (2/\sqrt(\pi)) \int_x^\infty \exp(-t^2).")
(defmfun log-erfc (x)
"gsl_sf_log_erfc_e" ((x :double) (ret sf-result))
"The logarithm of the complementary error function \log(\erfc(x)).")
(defmfun erf-Z (x)
"gsl_sf_erf_Z_e" ((x :double) (ret sf-result))
"The Gaussian probability density function
Z(x) = (1/sqrt{2\pi}) \exp(-x^2/2)}.")
(defmfun erf-Q (x)
"gsl_sf_erf_Q_e" ((x :double) (ret sf-result))
"The upper tail of the Gaussian probability function
Q(x) = (1/\sqrt{2\pi}) \int_x^\infty dt \exp(-t^2/2)}.")
(defmfun hazard (x)
"gsl_sf_hazard_e" ((x :double) (ret sf-result))
"The hazard function for the normal distribution.")
(save-test error-functions
(erf 1.0d0)
(erfc 1.0d0)
(log-erfc 1.0d0)
(erf-z 1.0d0)
(erf-q 1.0d0)
(hazard 1.0d0))
|
a6e57a084f94f5f9f83955c8b4c3c9fb35137a8f4f2ef5d45785bfb4ddcce3c8 | Cipherwraith/hblog | Input.hs | module Input where
import Config
import Types
import qualified Data.Text.Lazy as T
import qualified Data.Text.Lazy.IO as T
import System.Directory
import Data.List
import Control.Applicative
import System.FilePath
import Data.Char
import Text.Pandoc
getPostList :: IO [FilePath]
getPostList = map (postsDirectory </>) . delete "." . delete ".." <$> getDirectoryContents postsDirectory
getRawPost :: FilePath -> IO T.Text
getRawPost = T.readFile
parsePost :: T.Text -> Post
parsePost s = Post getTitle
getDate
getAuthor
getContentRaw
prettifyContent
where
splitInput
| length (T.lines s) < 4 = [e, e, e, e]
| otherwise = T.lines s
e = T.empty
removeNonNumbers :: String -> String
removeNonNumbers = filter isNumber
convertToInteger :: T.Text -> Integer
convertToInteger x = read . removeNonNumbers . T.unpack $ x :: Integer
getTitle = head splitInput
getDate = convertToInteger . head . drop 1 $ splitInput
getAuthor = head . drop 2 $ splitInput
getContentRaw = T.unlines . drop 3 $ splitInput
prettifyContent = prettify getContentRaw
prettify :: T.Text -> T.Text
prettify = T.pack . writeHtmlString def . readMarkdown def . T.unpack
markdownText = T.pack "hello\n\n*#dog*\n\n1. Red\n\n2. Blue\n\n3. Green\n\n* hi\n\n* dog\n\n[example](www.dog.com)\n\n this is code\n\n more code"
getPosts :: IO [Post]
getPosts = do
postList <- getPostList
rawPosts <- mapM getRawPost postList
let parsed = map parsePost rawPosts
return . reverse . sort $ parsed
| null | https://raw.githubusercontent.com/Cipherwraith/hblog/f92d96a60e301302c8a0e46fd68ee1e1810eb031/Input.hs | haskell | module Input where
import Config
import Types
import qualified Data.Text.Lazy as T
import qualified Data.Text.Lazy.IO as T
import System.Directory
import Data.List
import Control.Applicative
import System.FilePath
import Data.Char
import Text.Pandoc
getPostList :: IO [FilePath]
getPostList = map (postsDirectory </>) . delete "." . delete ".." <$> getDirectoryContents postsDirectory
getRawPost :: FilePath -> IO T.Text
getRawPost = T.readFile
parsePost :: T.Text -> Post
parsePost s = Post getTitle
getDate
getAuthor
getContentRaw
prettifyContent
where
splitInput
| length (T.lines s) < 4 = [e, e, e, e]
| otherwise = T.lines s
e = T.empty
removeNonNumbers :: String -> String
removeNonNumbers = filter isNumber
convertToInteger :: T.Text -> Integer
convertToInteger x = read . removeNonNumbers . T.unpack $ x :: Integer
getTitle = head splitInput
getDate = convertToInteger . head . drop 1 $ splitInput
getAuthor = head . drop 2 $ splitInput
getContentRaw = T.unlines . drop 3 $ splitInput
prettifyContent = prettify getContentRaw
prettify :: T.Text -> T.Text
prettify = T.pack . writeHtmlString def . readMarkdown def . T.unpack
markdownText = T.pack "hello\n\n*#dog*\n\n1. Red\n\n2. Blue\n\n3. Green\n\n* hi\n\n* dog\n\n[example](www.dog.com)\n\n this is code\n\n more code"
getPosts :: IO [Post]
getPosts = do
postList <- getPostList
rawPosts <- mapM getRawPost postList
let parsed = map parsePost rawPosts
return . reverse . sort $ parsed
| |
447f3cf0f757b9739c2a74aa8cd1c7208e87f578d953fd551d731684c896db34 | andrewmcloud/consimilo | text_processing.clj | (ns consimilo.text-processing
(:require [opennlp.nlp :as nlp]
[pantomime.extract :as extract]
[clojure.java.io :as io]
[clojure.string :as s]
[clojure.tools.logging :as log]))
(def ^:private tokenize (nlp/make-tokenizer (io/resource "en-token.bin")))
(def ^:private stopwords (set (s/split-lines (slurp (io/resource "stopwords.txt")))))
(defn- remove-stopwords
"If remove-stopwords?: returns tokenized-text with stopwords removed, else: returns tokenized-text unaltered"
[remove-stopwords? tokenized-text]
(if remove-stopwords?
(remove stopwords tokenized-text)
tokenized-text))
(defn tokenize-text
"Tokenizes a string of text. If remove-stopwords?: removes stopwords from token collection"
[text & {:keys [remove-stopwords?] :or {remove-stopwords? true}}]
(->> (s/lower-case text)
tokenize
(remove-stopwords remove-stopwords?)))
;;Not currently used
(defn shingle
"Generates contiguous sequences of tokens of length n, may be a better gauge of similarity when using consimilo
to query a text corpus for similarity. Generate tokenized-text via consimilo.text-processing/tokenize-text"
([tokenized-text n]
(if (and (> n 1) (<= n (count tokenized-text)))
(shingle tokenized-text n [])
(do
(log/warn "Invalid shingle size. Shingle size must be (1 < n <= tokenized-text) returning tokenized-text")
tokenized-text)))
([[first & rest] n coll]
(let [k (dec n)]
(if (not= k (count (take k rest)))
coll
(recur rest n (conj coll (->> rest
(take k)
(concat [first])
(apply str))))))))
(defn- parse-file-to-text
"Parse pdf calls extract/parse and catches an IndexOutOfBounds exception that is thrown by tika on rare occasion."
[file]
(try
(extract/parse file)
(catch IndexOutOfBoundsException e
(log/warn "Unable to extract text from pdf - filename: " (.getName file)))))
(defn extract-text
"Return extracted text by file content (as `java.io.File`)."
[file_obj]
(:text (parse-file-to-text file_obj)))
| null | https://raw.githubusercontent.com/andrewmcloud/consimilo/db96c1695248c3486e1d23de5589b39f0e0bd49f/src/consimilo/text_processing.clj | clojure | Not currently used | (ns consimilo.text-processing
(:require [opennlp.nlp :as nlp]
[pantomime.extract :as extract]
[clojure.java.io :as io]
[clojure.string :as s]
[clojure.tools.logging :as log]))
(def ^:private tokenize (nlp/make-tokenizer (io/resource "en-token.bin")))
(def ^:private stopwords (set (s/split-lines (slurp (io/resource "stopwords.txt")))))
(defn- remove-stopwords
"If remove-stopwords?: returns tokenized-text with stopwords removed, else: returns tokenized-text unaltered"
[remove-stopwords? tokenized-text]
(if remove-stopwords?
(remove stopwords tokenized-text)
tokenized-text))
(defn tokenize-text
"Tokenizes a string of text. If remove-stopwords?: removes stopwords from token collection"
[text & {:keys [remove-stopwords?] :or {remove-stopwords? true}}]
(->> (s/lower-case text)
tokenize
(remove-stopwords remove-stopwords?)))
(defn shingle
"Generates contiguous sequences of tokens of length n, may be a better gauge of similarity when using consimilo
to query a text corpus for similarity. Generate tokenized-text via consimilo.text-processing/tokenize-text"
([tokenized-text n]
(if (and (> n 1) (<= n (count tokenized-text)))
(shingle tokenized-text n [])
(do
(log/warn "Invalid shingle size. Shingle size must be (1 < n <= tokenized-text) returning tokenized-text")
tokenized-text)))
([[first & rest] n coll]
(let [k (dec n)]
(if (not= k (count (take k rest)))
coll
(recur rest n (conj coll (->> rest
(take k)
(concat [first])
(apply str))))))))
(defn- parse-file-to-text
"Parse pdf calls extract/parse and catches an IndexOutOfBounds exception that is thrown by tika on rare occasion."
[file]
(try
(extract/parse file)
(catch IndexOutOfBoundsException e
(log/warn "Unable to extract text from pdf - filename: " (.getName file)))))
(defn extract-text
"Return extracted text by file content (as `java.io.File`)."
[file_obj]
(:text (parse-file-to-text file_obj)))
|
7fc3cec0378e7af4c6903f5d5f258e35cd8e9810d983b641fde57ed4bbb9fc00 | foreverbell/project-euler-solutions | Matrix.hs | modified from -Diaz/matrix for my specific use .
module Common.Matrix.Matrix (
Matrix,
rows, cols,
fmap,
(!), (!.), getElem, safeGet, unsafeGet,
getRow, getCol,
fromList, toList, fromLists, toLists,
create,
zero, identity, scalar,
add, subtract, multiply,
power
) where
import Prelude hiding (subtract, fmap)
import Data.Bits (Bits, shiftR, (.&.))
import Data.Maybe (fromMaybe)
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector as RV
data V.Unbox a => Matrix a = Matrix {
rows :: {-# UNPACK #-} !Int,
cols :: {-# UNPACK #-} !Int,
vect :: V.Vector a
} deriving (Eq, Show)
encode :: Int -> (Int, Int) -> Int
# INLINE encode #
encode m (i, j) = (i - 1) * m + j - 1
fmap :: V.Unbox a => (a -> a) -> Matrix a -> Matrix a
# INLINE fmap #
fmap f (Matrix r c v) = Matrix r c $ V.map f v
getElem :: V.Unbox a => Int -> Int -> Matrix a -> a
# INLINE getElem #
getElem i j m = fromMaybe (error "getElem: out of bound.") (safeGet i j m)
(!) :: V.Unbox a => Matrix a -> (Int, Int) -> a
{-# INLINE (!) #-}
m ! (i, j) = getElem i j m
(!.) :: V.Unbox a => Matrix a -> (Int, Int) -> a
{-# INLINE (!.) #-}
m !. (i, j) = unsafeGet i j m
safeGet :: V.Unbox a => Int -> Int -> Matrix a -> Maybe a
# INLINE safeGet #
safeGet i j m@(Matrix r c _)
| i < 1 || j < 1 || i > r || j > c = Nothing
| otherwise = Just $ unsafeGet i j m
unsafeGet :: V.Unbox a => Int -> Int -> Matrix a -> a
# INLINE unsafeGet #
unsafeGet i j (Matrix _ c v) = V.unsafeIndex v $ encode c (i, j)
getRow :: V.Unbox a => Int -> Matrix a -> V.Vector a
# INLINE getRow #
getRow i (Matrix _ m v) = V.slice (m * (i - 1)) m v
getCol :: V.Unbox a => Int -> Matrix a -> V.Vector a
# INLINE getCol #
getCol j (Matrix n m v) = V.generate n $ \i -> v V.! encode m (i + 1, j)
create :: V.Unbox a => Int -> Int -> ((Int, Int) -> a) -> Matrix a
# INLINE create #
create n m f = Matrix n m $ V.fromList [ f (i, j) | i <- [1 .. n], j <- [1 .. m] ]
fromList :: V.Unbox a => Int -> Int -> [a] -> Matrix a
# INLINE fromList #
fromList n m = Matrix n m . V.fromListN (n * m)
fromLists :: V.Unbox a => [[a]] -> Matrix a
# INLINE fromLists #
fromLists [] = error "fromLists: empty list."
fromLists (xs:xss) = fromList n m $ concat $ xs : map (take m) xss where
n = 1 + length xss
m = length xs
toList :: V.Unbox a => Matrix a -> [a]
# INLINE toList #
toList m@(Matrix r c _) = [ unsafeGet i j m | i <- [1 .. r] , j <- [1 .. c] ]
toLists :: V.Unbox a => Matrix a -> [[a]]
# INLINE toLists #
toLists m@(Matrix r c _) = [ [ unsafeGet i j m | j <- [1 .. c] ] | i <- [1 .. r] ]
zero :: (V.Unbox a, Num a) => Int -> Int -> Matrix a
# INLINE zero #
zero n m = Matrix n m $ V.replicate (n * m) 0
scalar :: (V.Unbox a, Num a) => Int -> a -> Matrix a
# INLINE scalar #
scalar n x = create n n $ \(i, j) -> if i == j then x else 0
identity :: (V.Unbox a, Num a) => Int -> Matrix a
# INLINE identity #
identity n = scalar n 1
add :: (V.Unbox a, Num a) => Matrix a -> Matrix a -> Matrix a
# INLINE add #
add (Matrix r1 c1 v1) (Matrix r2 c2 v2)
| r1 == r2 && c1 == c2 = Matrix r1 c1 $ V.zipWith (+) v1 v2
| otherwise = error "add: matrix size not match."
subtract :: (V.Unbox a, Num a) => Matrix a -> Matrix a -> Matrix a
# INLINE subtract #
subtract (Matrix r1 c1 v1) (Matrix r2 c2 v2)
| r1 == r2 && c1 == c2 = Matrix r1 c1 $ V.zipWith (-) v1 v2
| otherwise = error "subtract: matrix size not match."
multiply :: (V.Unbox a, Num a) => Matrix a -> Matrix a -> Matrix a
# INLINE multiply #
multiply m1@(Matrix _ c _) m2@(Matrix r _ _)
| c == r = multiply' m1 m2
| otherwise = error "multiply: matrix size not match."
multiply' :: (V.Unbox a, Num a) => Matrix a -> Matrix a -> Matrix a
# INLINE multiply ' #
multiply' m1@(Matrix r _ _) m2@(Matrix _ c _) = create r c $ \(i, j) -> dotProduct (RV.unsafeIndex avs $ i - 1) (RV.unsafeIndex bvs $ j - 1) where
avs = RV.generate r $ \i -> getRow (i + 1) m1
bvs = RV.generate c $ \i -> getCol (i + 1) m2
dotProduct v1 v2 = V.foldl' (+) 0 $ V.zipWith (*) v1 v2
power :: (Integral a, Bits a, V.Unbox b, Num b) => Matrix b -> a -> Matrix b
# INLINE power #
power m@(Matrix r c _) p
| r == c = helper m p $ identity r
| otherwise = error "power: matrix not squared."
where
helper _ 0 ret = ret
helper a x ret = if (x .&. 1) == 1
then helper a' x' (multiply' ret a)
else helper a' x' ret where
a' = multiply' a a
x' = x `shiftR` 1
| null | https://raw.githubusercontent.com/foreverbell/project-euler-solutions/c0bf2746aafce9be510892814e2d03e20738bf2b/lib/Common/Matrix/Matrix.hs | haskell | # UNPACK #
# UNPACK #
# INLINE (!) #
# INLINE (!.) # | modified from -Diaz/matrix for my specific use .
module Common.Matrix.Matrix (
Matrix,
rows, cols,
fmap,
(!), (!.), getElem, safeGet, unsafeGet,
getRow, getCol,
fromList, toList, fromLists, toLists,
create,
zero, identity, scalar,
add, subtract, multiply,
power
) where
import Prelude hiding (subtract, fmap)
import Data.Bits (Bits, shiftR, (.&.))
import Data.Maybe (fromMaybe)
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector as RV
data V.Unbox a => Matrix a = Matrix {
vect :: V.Vector a
} deriving (Eq, Show)
encode :: Int -> (Int, Int) -> Int
# INLINE encode #
encode m (i, j) = (i - 1) * m + j - 1
fmap :: V.Unbox a => (a -> a) -> Matrix a -> Matrix a
# INLINE fmap #
fmap f (Matrix r c v) = Matrix r c $ V.map f v
getElem :: V.Unbox a => Int -> Int -> Matrix a -> a
# INLINE getElem #
getElem i j m = fromMaybe (error "getElem: out of bound.") (safeGet i j m)
(!) :: V.Unbox a => Matrix a -> (Int, Int) -> a
m ! (i, j) = getElem i j m
(!.) :: V.Unbox a => Matrix a -> (Int, Int) -> a
m !. (i, j) = unsafeGet i j m
safeGet :: V.Unbox a => Int -> Int -> Matrix a -> Maybe a
# INLINE safeGet #
safeGet i j m@(Matrix r c _)
| i < 1 || j < 1 || i > r || j > c = Nothing
| otherwise = Just $ unsafeGet i j m
unsafeGet :: V.Unbox a => Int -> Int -> Matrix a -> a
# INLINE unsafeGet #
unsafeGet i j (Matrix _ c v) = V.unsafeIndex v $ encode c (i, j)
getRow :: V.Unbox a => Int -> Matrix a -> V.Vector a
# INLINE getRow #
getRow i (Matrix _ m v) = V.slice (m * (i - 1)) m v
getCol :: V.Unbox a => Int -> Matrix a -> V.Vector a
# INLINE getCol #
getCol j (Matrix n m v) = V.generate n $ \i -> v V.! encode m (i + 1, j)
create :: V.Unbox a => Int -> Int -> ((Int, Int) -> a) -> Matrix a
# INLINE create #
create n m f = Matrix n m $ V.fromList [ f (i, j) | i <- [1 .. n], j <- [1 .. m] ]
fromList :: V.Unbox a => Int -> Int -> [a] -> Matrix a
# INLINE fromList #
fromList n m = Matrix n m . V.fromListN (n * m)
fromLists :: V.Unbox a => [[a]] -> Matrix a
# INLINE fromLists #
fromLists [] = error "fromLists: empty list."
fromLists (xs:xss) = fromList n m $ concat $ xs : map (take m) xss where
n = 1 + length xss
m = length xs
toList :: V.Unbox a => Matrix a -> [a]
# INLINE toList #
toList m@(Matrix r c _) = [ unsafeGet i j m | i <- [1 .. r] , j <- [1 .. c] ]
toLists :: V.Unbox a => Matrix a -> [[a]]
# INLINE toLists #
toLists m@(Matrix r c _) = [ [ unsafeGet i j m | j <- [1 .. c] ] | i <- [1 .. r] ]
zero :: (V.Unbox a, Num a) => Int -> Int -> Matrix a
# INLINE zero #
zero n m = Matrix n m $ V.replicate (n * m) 0
scalar :: (V.Unbox a, Num a) => Int -> a -> Matrix a
# INLINE scalar #
scalar n x = create n n $ \(i, j) -> if i == j then x else 0
identity :: (V.Unbox a, Num a) => Int -> Matrix a
# INLINE identity #
identity n = scalar n 1
add :: (V.Unbox a, Num a) => Matrix a -> Matrix a -> Matrix a
# INLINE add #
add (Matrix r1 c1 v1) (Matrix r2 c2 v2)
| r1 == r2 && c1 == c2 = Matrix r1 c1 $ V.zipWith (+) v1 v2
| otherwise = error "add: matrix size not match."
subtract :: (V.Unbox a, Num a) => Matrix a -> Matrix a -> Matrix a
# INLINE subtract #
subtract (Matrix r1 c1 v1) (Matrix r2 c2 v2)
| r1 == r2 && c1 == c2 = Matrix r1 c1 $ V.zipWith (-) v1 v2
| otherwise = error "subtract: matrix size not match."
multiply :: (V.Unbox a, Num a) => Matrix a -> Matrix a -> Matrix a
# INLINE multiply #
multiply m1@(Matrix _ c _) m2@(Matrix r _ _)
| c == r = multiply' m1 m2
| otherwise = error "multiply: matrix size not match."
multiply' :: (V.Unbox a, Num a) => Matrix a -> Matrix a -> Matrix a
# INLINE multiply ' #
multiply' m1@(Matrix r _ _) m2@(Matrix _ c _) = create r c $ \(i, j) -> dotProduct (RV.unsafeIndex avs $ i - 1) (RV.unsafeIndex bvs $ j - 1) where
avs = RV.generate r $ \i -> getRow (i + 1) m1
bvs = RV.generate c $ \i -> getCol (i + 1) m2
dotProduct v1 v2 = V.foldl' (+) 0 $ V.zipWith (*) v1 v2
power :: (Integral a, Bits a, V.Unbox b, Num b) => Matrix b -> a -> Matrix b
# INLINE power #
power m@(Matrix r c _) p
| r == c = helper m p $ identity r
| otherwise = error "power: matrix not squared."
where
helper _ 0 ret = ret
helper a x ret = if (x .&. 1) == 1
then helper a' x' (multiply' ret a)
else helper a' x' ret where
a' = multiply' a a
x' = x `shiftR` 1
|
8baf4c2d267a274be537e0b866f246082f9aa36d2f362a58471263748eeaaa48 | nuprl/gradual-typing-performance | array-struct-unsafe-build-array.rkt | #lang typed/racket/base
(provide unsafe-build-array)
;; -----------------------------------------------------------------------------
(require "type-aliases.rkt"
"data-array-adapted.rkt"
(only-in racket/fixnum fx+ fx*)
benchmark-util)
(require/typed/check "array-utils-check-array-shape.rkt"
[check-array-shape (-> (Vectorof Integer) (-> Nothing) Indexes)])
(require/typed/check "array-utils-check-array-shape-size.rkt"
[check-array-shape-size (-> Symbol Indexes Integer)])
(require/typed/check "array-utils-unsafe-array-index-value-index.rkt"
[unsafe-array-index->value-index (-> Indexes Indexes Integer)])
;; =============================================================================
(: unsafe-build-array ((Vectorof Integer) ((Vectorof Integer) -> Float) -> Array))
(define (unsafe-build-array ds f)
;; This box's contents get replaced when the array we're constructing is made strict, so that
;; the array stops referencing f. If we didn't do this, long chains of array computations would
;; keep hold of references to all the intermediate procs, which is a memory leak.
(let ([f (box f)])
(define size (check-array-shape-size 'unsafe-build-array ds))
Sharp readers might notice that strict ! does n't check to see whether the array is already
;; strict; that's okay - array-strict! does it instead, which makes the "once strict, always
;; strict" invariant easier to ensure in subtypes, which we don't always have control over
(define (strict!)
(let* ([old-f : (-> (Vectorof Integer) Float) (unbox f)]
[vs : (Vectorof Float) (inline-build-array-data ds (lambda (js j) (old-f js)) Float)])
;; Make a new f that just indexes into vs
(set-box! f (λ: ([js : Indexes])
(vector-ref vs (unsafe-array-index->value-index ds js))))))
(define unsafe-proc
(λ: ([js : Indexes]) ((unbox f) js)))
(Array ds size ((inst box Boolean) #f) strict! unsafe-proc)))
;; -----------------------------------------------------------------------------
;; -- helper macros
(define-syntax-rule (for-each-array+data-index ds-expr f-expr)
(let*: ([ds : Indexes ds-expr]
[dims : Integer (vector-length ds)])
(define-syntax-rule (f js j)
((ann f-expr (Indexes Integer -> Void)) js j))
(cond
[(= dims 0) (f ds 0)]
[else
(define: js : Indexes (make-vector dims 0))
(case dims
[(1) (define: d0 : Integer (vector-ref ds 0))
(let: j0-loop : Void ([j0 : Integer 0])
(when (j0 . < . d0)
(vector-set! js 0 j0)
(f js j0)
(j0-loop (+ j0 1))))]
[(2) (define: d0 : Integer (vector-ref ds 0))
(define: d1 : Integer (vector-ref ds 1))
(let: j0-loop : Void ([j0 : Integer 0]
[j : Integer 0])
(when (j0 . < . d0)
(vector-set! js 0 j0)
(let: j1-loop : Void ([j1 : Integer 0]
[j : Integer j])
(cond [(j1 . < . d1)
(vector-set! js 1 j1)
(f js j)
(j1-loop (+ j1 1) (fx+ j 1))]
[else
(j0-loop (+ j0 1) j)]))))]
[else (let: i-loop : Integer ([i : Integer 0]
[j : Integer 0])
(cond [(i . < . dims)
(define: di : Integer (vector-ref ds i))
(let: ji-loop : Integer ([ji : Integer 0]
[j : Integer j])
(cond [(ji . < . di)
(vector-set! js i ji)
(ji-loop (+ ji 1) (i-loop (+ i 1) j))]
[else j]))]
[else (f js j)
(fx+ j 1)]))
(void)])])))
(define-syntax-rule (for-each-array-index ds-expr f-expr)
(let*: ([ds : Indexes ds-expr]
[dims : Integer (vector-length ds)])
(define-syntax-rule (f js)
((ann f-expr (Indexes -> Void)) js))
(cond
[(= dims 0) (f ds)]
[else
(define: js : Indexes (make-vector dims 0))
(case dims
[(1) (define: d0 : Integer (vector-ref ds 0))
(let: j0-loop : Void ([j0 : Integer 0])
(when (j0 . < . d0)
(vector-set! js 0 j0)
(f js)
(j0-loop (+ j0 1))))]
[(2) (define: d0 : Integer (vector-ref ds 0))
(define: d1 : Integer (vector-ref ds 1))
(let: j0-loop : Void ([j0 : Integer 0])
(when (j0 . < . d0)
(vector-set! js 0 j0)
(let: j1-loop : Void ([j1 : Integer 0])
(cond [(j1 . < . d1)
(vector-set! js 1 j1)
(f js)
(j1-loop (+ j1 1))]
[else
(j0-loop (+ j0 1))]))))]
[else (let: i-loop : Void ([i : Integer 0])
(cond [(i . < . dims)
(define: di : Integer (vector-ref ds i))
(let: ji-loop : Void ([ji : Integer 0])
(when (ji . < . di)
(vector-set! js i ji)
(i-loop (+ i 1))
(ji-loop (+ ji 1))))]
[else (f js)]))])])))
(define-syntax-rule (for-each-data-index ds-expr f-expr)
(let*: ([ds : Indexes ds-expr]
[dims : Integer (vector-length ds)])
(define-syntax-rule (f j)
((ann f-expr (Integer -> Void)) j))
(cond
[(= dims 0) (f 0)]
[else
(case dims
[(1) (define: d0 : Integer (vector-ref ds 0))
(let: j0-loop : Void ([j0 : Integer 0])
(when (j0 . < . d0)
(f j0)
(j0-loop (+ j0 1))))]
[(2) (define: d0 : Integer (vector-ref ds 0))
(define: d1 : Integer (vector-ref ds 1))
(let: j0-loop : Void ([j0 : Integer 0]
[j : Integer 0])
(when (j0 . < . d0)
(let: j1-loop : Void ([j1 : Integer 0]
[j : Integer j])
(cond [(j1 . < . d1)
(f j)
(j1-loop (+ j1 1) (fx+ j 1))]
[else
(j0-loop (+ j0 1) j)]))))]
[else (let: i-loop : Integer ([i : Integer 0]
[j : Integer 0])
(cond [(i . < . dims)
(define: di : Integer (vector-ref ds i))
(let: ji-loop : Integer ([ji : Integer 0]
[j : Integer j])
(cond [(ji . < . di)
(ji-loop (+ ji 1) (i-loop (+ i 1) j))]
[else j]))]
[else (f j)
(fx+ j 1)]))
(void)])])))
(define-syntax-rule (inline-build-array-data ds-expr g-expr A)
(let*: ([ds : Indexes ds-expr]
[dims : Integer (vector-length ds)])
(define-syntax-rule (g js j)
((ann g-expr (Indexes Integer -> A)) js j))
(define: size : Integer
(let: loop : Integer ([k : Integer 0] [size : Integer 1])
(cond [(k . < . dims) (loop (+ k 1) (fx* size (vector-ref ds k)))]
[else size])))
(cond [(= size 0) (ann (vector) (Vectorof A))]
[else
(define: js0 : Indexes (make-vector dims 0))
(define: vs : (Vectorof A) (make-vector size (g js0 0)))
(for-each-array+data-index ds (λ (js j) (vector-set! vs j (g js j))))
vs])))
| null | https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/experimental/micro/synth/typed/array-struct-unsafe-build-array.rkt | racket | -----------------------------------------------------------------------------
=============================================================================
This box's contents get replaced when the array we're constructing is made strict, so that
the array stops referencing f. If we didn't do this, long chains of array computations would
keep hold of references to all the intermediate procs, which is a memory leak.
strict; that's okay - array-strict! does it instead, which makes the "once strict, always
strict" invariant easier to ensure in subtypes, which we don't always have control over
Make a new f that just indexes into vs
-----------------------------------------------------------------------------
-- helper macros | #lang typed/racket/base
(provide unsafe-build-array)
(require "type-aliases.rkt"
"data-array-adapted.rkt"
(only-in racket/fixnum fx+ fx*)
benchmark-util)
(require/typed/check "array-utils-check-array-shape.rkt"
[check-array-shape (-> (Vectorof Integer) (-> Nothing) Indexes)])
(require/typed/check "array-utils-check-array-shape-size.rkt"
[check-array-shape-size (-> Symbol Indexes Integer)])
(require/typed/check "array-utils-unsafe-array-index-value-index.rkt"
[unsafe-array-index->value-index (-> Indexes Indexes Integer)])
(: unsafe-build-array ((Vectorof Integer) ((Vectorof Integer) -> Float) -> Array))
(define (unsafe-build-array ds f)
(let ([f (box f)])
(define size (check-array-shape-size 'unsafe-build-array ds))
Sharp readers might notice that strict ! does n't check to see whether the array is already
(define (strict!)
(let* ([old-f : (-> (Vectorof Integer) Float) (unbox f)]
[vs : (Vectorof Float) (inline-build-array-data ds (lambda (js j) (old-f js)) Float)])
(set-box! f (λ: ([js : Indexes])
(vector-ref vs (unsafe-array-index->value-index ds js))))))
(define unsafe-proc
(λ: ([js : Indexes]) ((unbox f) js)))
(Array ds size ((inst box Boolean) #f) strict! unsafe-proc)))
(define-syntax-rule (for-each-array+data-index ds-expr f-expr)
(let*: ([ds : Indexes ds-expr]
[dims : Integer (vector-length ds)])
(define-syntax-rule (f js j)
((ann f-expr (Indexes Integer -> Void)) js j))
(cond
[(= dims 0) (f ds 0)]
[else
(define: js : Indexes (make-vector dims 0))
(case dims
[(1) (define: d0 : Integer (vector-ref ds 0))
(let: j0-loop : Void ([j0 : Integer 0])
(when (j0 . < . d0)
(vector-set! js 0 j0)
(f js j0)
(j0-loop (+ j0 1))))]
[(2) (define: d0 : Integer (vector-ref ds 0))
(define: d1 : Integer (vector-ref ds 1))
(let: j0-loop : Void ([j0 : Integer 0]
[j : Integer 0])
(when (j0 . < . d0)
(vector-set! js 0 j0)
(let: j1-loop : Void ([j1 : Integer 0]
[j : Integer j])
(cond [(j1 . < . d1)
(vector-set! js 1 j1)
(f js j)
(j1-loop (+ j1 1) (fx+ j 1))]
[else
(j0-loop (+ j0 1) j)]))))]
[else (let: i-loop : Integer ([i : Integer 0]
[j : Integer 0])
(cond [(i . < . dims)
(define: di : Integer (vector-ref ds i))
(let: ji-loop : Integer ([ji : Integer 0]
[j : Integer j])
(cond [(ji . < . di)
(vector-set! js i ji)
(ji-loop (+ ji 1) (i-loop (+ i 1) j))]
[else j]))]
[else (f js j)
(fx+ j 1)]))
(void)])])))
(define-syntax-rule (for-each-array-index ds-expr f-expr)
(let*: ([ds : Indexes ds-expr]
[dims : Integer (vector-length ds)])
(define-syntax-rule (f js)
((ann f-expr (Indexes -> Void)) js))
(cond
[(= dims 0) (f ds)]
[else
(define: js : Indexes (make-vector dims 0))
(case dims
[(1) (define: d0 : Integer (vector-ref ds 0))
(let: j0-loop : Void ([j0 : Integer 0])
(when (j0 . < . d0)
(vector-set! js 0 j0)
(f js)
(j0-loop (+ j0 1))))]
[(2) (define: d0 : Integer (vector-ref ds 0))
(define: d1 : Integer (vector-ref ds 1))
(let: j0-loop : Void ([j0 : Integer 0])
(when (j0 . < . d0)
(vector-set! js 0 j0)
(let: j1-loop : Void ([j1 : Integer 0])
(cond [(j1 . < . d1)
(vector-set! js 1 j1)
(f js)
(j1-loop (+ j1 1))]
[else
(j0-loop (+ j0 1))]))))]
[else (let: i-loop : Void ([i : Integer 0])
(cond [(i . < . dims)
(define: di : Integer (vector-ref ds i))
(let: ji-loop : Void ([ji : Integer 0])
(when (ji . < . di)
(vector-set! js i ji)
(i-loop (+ i 1))
(ji-loop (+ ji 1))))]
[else (f js)]))])])))
(define-syntax-rule (for-each-data-index ds-expr f-expr)
(let*: ([ds : Indexes ds-expr]
[dims : Integer (vector-length ds)])
(define-syntax-rule (f j)
((ann f-expr (Integer -> Void)) j))
(cond
[(= dims 0) (f 0)]
[else
(case dims
[(1) (define: d0 : Integer (vector-ref ds 0))
(let: j0-loop : Void ([j0 : Integer 0])
(when (j0 . < . d0)
(f j0)
(j0-loop (+ j0 1))))]
[(2) (define: d0 : Integer (vector-ref ds 0))
(define: d1 : Integer (vector-ref ds 1))
(let: j0-loop : Void ([j0 : Integer 0]
[j : Integer 0])
(when (j0 . < . d0)
(let: j1-loop : Void ([j1 : Integer 0]
[j : Integer j])
(cond [(j1 . < . d1)
(f j)
(j1-loop (+ j1 1) (fx+ j 1))]
[else
(j0-loop (+ j0 1) j)]))))]
[else (let: i-loop : Integer ([i : Integer 0]
[j : Integer 0])
(cond [(i . < . dims)
(define: di : Integer (vector-ref ds i))
(let: ji-loop : Integer ([ji : Integer 0]
[j : Integer j])
(cond [(ji . < . di)
(ji-loop (+ ji 1) (i-loop (+ i 1) j))]
[else j]))]
[else (f j)
(fx+ j 1)]))
(void)])])))
(define-syntax-rule (inline-build-array-data ds-expr g-expr A)
(let*: ([ds : Indexes ds-expr]
[dims : Integer (vector-length ds)])
(define-syntax-rule (g js j)
((ann g-expr (Indexes Integer -> A)) js j))
(define: size : Integer
(let: loop : Integer ([k : Integer 0] [size : Integer 1])
(cond [(k . < . dims) (loop (+ k 1) (fx* size (vector-ref ds k)))]
[else size])))
(cond [(= size 0) (ann (vector) (Vectorof A))]
[else
(define: js0 : Indexes (make-vector dims 0))
(define: vs : (Vectorof A) (make-vector size (g js0 0)))
(for-each-array+data-index ds (λ (js j) (vector-set! vs j (g js j))))
vs])))
|
6ab60662fb5e9634e39eb8ba4bc1b0a4fc0db46b28c8862fed85c8824262fb30 | google/proto-lens | Wire.hs | | Module defining the individual base wire types ( e.g. VarInt , Fixed64 ) .
--
-- They are used to represent the @unknownFields@ within the proto message.
--
-- Upstream docs:
-- <-buffers/docs/encoding#structure>
{-# LANGUAGE BangPatterns #-}
# LANGUAGE CPP #
# LANGUAGE GeneralizedNewtypeDeriving #
module Data.ProtoLens.Encoding.Wire
( Tag(..)
, TaggedValue(..)
, WireValue(..)
, FieldSet
, splitTypeAndTag
, joinTypeAndTag
, parseFieldSet
, buildFieldSet
, buildMessageSet
, parseTaggedValueFromWire
, parseMessageSetTaggedValueFromWire
) where
import Control.DeepSeq (NFData(..))
import Data.Bits ((.&.), (.|.), shiftL, shiftR)
import qualified Data.ByteString as B
#if !MIN_VERSION_base(4,11,0)
import Data.Semigroup ((<>))
#endif
import Data.Word (Word8, Word32, Word64)
import Data.ProtoLens.Encoding.Bytes
-- | A tag that identifies a particular field of the message when converting
-- to/from the wire format.
newtype Tag = Tag { unTag :: Int }
deriving (Show, Eq, Ord, Num, NFData)
-- | The encoding of some unknown field on the wire.
data WireValue
= VarInt !Word64
| Fixed64 !Word64
| Lengthy !B.ByteString
| StartGroup
| EndGroup
| Fixed32 !Word32
deriving (Eq, Ord)
-- | A pair of an encoded field and a value.
data TaggedValue = TaggedValue !Tag !WireValue
deriving (Eq, Ord)
type FieldSet = [TaggedValue]
TaggedValue , WireValue and Tag are strict , so their NFData instances are
-- trivial:
instance NFData TaggedValue where
rnf = (`seq` ())
instance NFData WireValue where
rnf = (`seq` ())
buildTaggedValue :: TaggedValue -> Builder
buildTaggedValue (TaggedValue tag wv) =
putVarInt (joinTypeAndTag tag (wireValueToInt wv))
<> buildWireValue wv
builds in legacy MessageSet format .
-- See #L444
buildTaggedValueAsMessageSet :: TaggedValue -> Builder
buildTaggedValueAsMessageSet (TaggedValue (Tag t) wv) =
buildTaggedValue ( TaggedValue 1 StartGroup)
<> buildTaggedValue (TaggedValue 2 (VarInt $ fromIntegral t))
<> buildTaggedValue (TaggedValue 3 wv)
<> buildTaggedValue (TaggedValue 1 EndGroup)
buildWireValue :: WireValue -> Builder
buildWireValue (VarInt w) = putVarInt w
buildWireValue (Fixed64 w) = putFixed64 w
buildWireValue (Fixed32 w) = putFixed32 w
buildWireValue (Lengthy b) =
putVarInt (fromIntegral $ B.length b)
<> putBytes b
buildWireValue StartGroup = mempty
buildWireValue EndGroup = mempty
wireValueToInt :: WireValue -> Word8
wireValueToInt VarInt{} = 0
wireValueToInt Fixed64{} = 1
wireValueToInt Lengthy{} = 2
wireValueToInt StartGroup{} = 3
wireValueToInt EndGroup{} = 4
wireValueToInt Fixed32{} = 5
parseTaggedValue :: Parser TaggedValue
parseTaggedValue = getVarInt >>= parseTaggedValueFromWire
parseTaggedValueFromWire :: Word64 -> Parser TaggedValue
parseTaggedValueFromWire t =
let (tag, w) = splitTypeAndTag t
in TaggedValue tag <$> case w of
0 -> VarInt <$> getVarInt
1 -> Fixed64 <$> getFixed64
2 -> Lengthy <$> do
len <- getVarInt
getBytes $ fromIntegral len
3 -> return StartGroup
4 -> return EndGroup
5 -> Fixed32 <$> getFixed32
_ -> fail $ "Unknown wire type " ++ show w
parseMessageSetTaggedValueFromWire :: Word64 -> Parser TaggedValue
parseMessageSetTaggedValueFromWire t =
parseTaggedValueFromWire t >>= \v -> case v of
TaggedValue 1 StartGroup -> parseTaggedValue >>= \ft -> case ft of
TaggedValue 2 (VarInt f) -> parseTaggedValue >>= \dt -> case dt of
TaggedValue 3 (Lengthy b) -> parseTaggedValue >>= \et -> case et of
TaggedValue 1 EndGroup -> return $ TaggedValue (Tag $ fromIntegral f) (Lengthy b)
_ -> fail "missing end_group"
_ -> fail "missing message"
_ -> fail "missing field tag"
_ -> return v
splitTypeAndTag :: Word64 -> (Tag, Word8)
splitTypeAndTag w = (fromIntegral $ w `shiftR` 3, fromIntegral (w .&. 7))
joinTypeAndTag :: Tag -> Word8 -> Word64
joinTypeAndTag (Tag t) w = fromIntegral t `shiftL` 3 .|. fromIntegral w
parseFieldSet :: Parser FieldSet
parseFieldSet = loop []
where
loop ws = do
end <- atEnd
if end
then return $! reverse ws
else do
!w <- parseTaggedValue
loop (w:ws)
buildFieldSet :: FieldSet -> Builder
buildFieldSet = mconcat . map buildTaggedValue
buildMessageSet :: FieldSet -> Builder
buildMessageSet = mconcat . map buildTaggedValueAsMessageSet
| null | https://raw.githubusercontent.com/google/proto-lens/081815877430afc1db669ca5e4edde1558b5fd9d/proto-lens/src/Data/ProtoLens/Encoding/Wire.hs | haskell |
They are used to represent the @unknownFields@ within the proto message.
Upstream docs:
<-buffers/docs/encoding#structure>
# LANGUAGE BangPatterns #
| A tag that identifies a particular field of the message when converting
to/from the wire format.
| The encoding of some unknown field on the wire.
| A pair of an encoded field and a value.
trivial:
See #L444 | | Module defining the individual base wire types ( e.g. VarInt , Fixed64 ) .
# LANGUAGE CPP #
# LANGUAGE GeneralizedNewtypeDeriving #
module Data.ProtoLens.Encoding.Wire
( Tag(..)
, TaggedValue(..)
, WireValue(..)
, FieldSet
, splitTypeAndTag
, joinTypeAndTag
, parseFieldSet
, buildFieldSet
, buildMessageSet
, parseTaggedValueFromWire
, parseMessageSetTaggedValueFromWire
) where
import Control.DeepSeq (NFData(..))
import Data.Bits ((.&.), (.|.), shiftL, shiftR)
import qualified Data.ByteString as B
#if !MIN_VERSION_base(4,11,0)
import Data.Semigroup ((<>))
#endif
import Data.Word (Word8, Word32, Word64)
import Data.ProtoLens.Encoding.Bytes
newtype Tag = Tag { unTag :: Int }
deriving (Show, Eq, Ord, Num, NFData)
data WireValue
= VarInt !Word64
| Fixed64 !Word64
| Lengthy !B.ByteString
| StartGroup
| EndGroup
| Fixed32 !Word32
deriving (Eq, Ord)
data TaggedValue = TaggedValue !Tag !WireValue
deriving (Eq, Ord)
type FieldSet = [TaggedValue]
TaggedValue , WireValue and Tag are strict , so their NFData instances are
instance NFData TaggedValue where
rnf = (`seq` ())
instance NFData WireValue where
rnf = (`seq` ())
buildTaggedValue :: TaggedValue -> Builder
buildTaggedValue (TaggedValue tag wv) =
putVarInt (joinTypeAndTag tag (wireValueToInt wv))
<> buildWireValue wv
builds in legacy MessageSet format .
buildTaggedValueAsMessageSet :: TaggedValue -> Builder
buildTaggedValueAsMessageSet (TaggedValue (Tag t) wv) =
buildTaggedValue ( TaggedValue 1 StartGroup)
<> buildTaggedValue (TaggedValue 2 (VarInt $ fromIntegral t))
<> buildTaggedValue (TaggedValue 3 wv)
<> buildTaggedValue (TaggedValue 1 EndGroup)
buildWireValue :: WireValue -> Builder
buildWireValue (VarInt w) = putVarInt w
buildWireValue (Fixed64 w) = putFixed64 w
buildWireValue (Fixed32 w) = putFixed32 w
buildWireValue (Lengthy b) =
putVarInt (fromIntegral $ B.length b)
<> putBytes b
buildWireValue StartGroup = mempty
buildWireValue EndGroup = mempty
wireValueToInt :: WireValue -> Word8
wireValueToInt VarInt{} = 0
wireValueToInt Fixed64{} = 1
wireValueToInt Lengthy{} = 2
wireValueToInt StartGroup{} = 3
wireValueToInt EndGroup{} = 4
wireValueToInt Fixed32{} = 5
parseTaggedValue :: Parser TaggedValue
parseTaggedValue = getVarInt >>= parseTaggedValueFromWire
parseTaggedValueFromWire :: Word64 -> Parser TaggedValue
parseTaggedValueFromWire t =
let (tag, w) = splitTypeAndTag t
in TaggedValue tag <$> case w of
0 -> VarInt <$> getVarInt
1 -> Fixed64 <$> getFixed64
2 -> Lengthy <$> do
len <- getVarInt
getBytes $ fromIntegral len
3 -> return StartGroup
4 -> return EndGroup
5 -> Fixed32 <$> getFixed32
_ -> fail $ "Unknown wire type " ++ show w
parseMessageSetTaggedValueFromWire :: Word64 -> Parser TaggedValue
parseMessageSetTaggedValueFromWire t =
parseTaggedValueFromWire t >>= \v -> case v of
TaggedValue 1 StartGroup -> parseTaggedValue >>= \ft -> case ft of
TaggedValue 2 (VarInt f) -> parseTaggedValue >>= \dt -> case dt of
TaggedValue 3 (Lengthy b) -> parseTaggedValue >>= \et -> case et of
TaggedValue 1 EndGroup -> return $ TaggedValue (Tag $ fromIntegral f) (Lengthy b)
_ -> fail "missing end_group"
_ -> fail "missing message"
_ -> fail "missing field tag"
_ -> return v
splitTypeAndTag :: Word64 -> (Tag, Word8)
splitTypeAndTag w = (fromIntegral $ w `shiftR` 3, fromIntegral (w .&. 7))
joinTypeAndTag :: Tag -> Word8 -> Word64
joinTypeAndTag (Tag t) w = fromIntegral t `shiftL` 3 .|. fromIntegral w
parseFieldSet :: Parser FieldSet
parseFieldSet = loop []
where
loop ws = do
end <- atEnd
if end
then return $! reverse ws
else do
!w <- parseTaggedValue
loop (w:ws)
buildFieldSet :: FieldSet -> Builder
buildFieldSet = mconcat . map buildTaggedValue
buildMessageSet :: FieldSet -> Builder
buildMessageSet = mconcat . map buildTaggedValueAsMessageSet
|
3f8a78b136f570624ec6733625d9ebddfb2f903d160c3c81836cf6ae10e2964f | input-output-hk/plutus-apps | Utils.hs | {-# LANGUAGE DataKinds #-}
# LANGUAGE DerivingStrategies #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TypeApplications #
module Plutus.Blockfrost.Utils where
import Data.Maybe (fromJust, fromMaybe)
import Data.Proxy (Proxy (..))
import Data.String
import Data.Text (Text, pack, unpack)
import Data.Text qualified as Text (drop, take)
import Text.Hex (decodeHex, encodeHex)
import Text.Read (readMaybe)
import Blockfrost.Client as Blockfrost
import Cardano.Api qualified as C
import Cardano.Api.Shelley qualified as Api
import Ledger.Slot qualified as Ledger (Slot (..), SlotRange)
import Ledger.Tx (TxOutRef (..))
import Ledger.Tx qualified as LT (ScriptTag (..), TxId (TxId))
import Ledger.Tx.CardanoAPI
import Ledger.Value.CardanoAPI qualified as Value
import Money (Approximation (Round), DecimalConf (..), SomeDiscrete, UnitScale, defaultDecimalConf, discreteToDecimal,
scale, someDiscreteAmount, someDiscreteCurrency)
import Plutus.V1.Ledger.Address qualified as LA
import Plutus.V1.Ledger.Api (Credential (..), fromBuiltin, toBuiltin, unCurrencySymbol, unTokenName)
import Plutus.V1.Ledger.Api qualified (DatumHash, RedeemerHash)
import Plutus.V1.Ledger.Interval (always, from, interval, to)
import Plutus.V1.Ledger.Scripts qualified as PS
import Plutus.V1.Ledger.Value (AssetClass, unAssetClass)
class Show a => ToBlockfrostScriptHash a where
toBlockfrostScriptHash :: a -> Blockfrost.ScriptHash
toBlockfrostScriptHash = fromString . show
instance ToBlockfrostScriptHash PS.ValidatorHash
instance ToBlockfrostScriptHash PS.MintingPolicyHash
instance ToBlockfrostScriptHash PS.StakeValidatorHash
class Show a => ToBlockfrostDatumHash a where
toBlockfrostDatumHash :: a -> Blockfrost.DatumHash
toBlockfrostDatumHash = fromString . show
instance ToBlockfrostDatumHash Plutus.V1.Ledger.Api.DatumHash
instance ToBlockfrostDatumHash Plutus.V1.Ledger.Api.RedeemerHash
toBlockfrostTxHash :: LT.TxId -> TxHash
toBlockfrostTxHash = TxHash . pack . show
toBlockfrostTxHashes :: [LT.TxId] -> [TxHash]
toBlockfrostTxHashes = map toBlockfrostTxHash
toBlockfrostRef :: TxOutRef -> (TxHash, Integer)
toBlockfrostRef ref = (toBlockfrostTxHash (txOutRefId ref), txOutRefIdx ref)
toBlockfrostAssetId :: AssetClass -> AssetId
toBlockfrostAssetId ac = fromString (polId ++ tName)
where
(cs, tn) = unAssetClass ac
polId :: String
polId = (unpack . encodeHex . fromBuiltin . unCurrencySymbol) cs
tName :: String
tName = (unpack . encodeHex . fromBuiltin . unTokenName) tn
textToDatumHash :: Text -> PS.DatumHash
textToDatumHash = PS.DatumHash . toBuiltin . fromJust . decodeHex
textToScriptHash :: Text -> PS.ScriptHash
textToScriptHash = PS.ScriptHash . toBuiltin . fromJust . decodeHex
textToRedeemerHash :: Text -> PS.RedeemerHash
textToRedeemerHash = PS.RedeemerHash . toBuiltin . fromJust . decodeHex
toPlutusScriptTag :: ValidationPurpose -> LT.ScriptTag
toPlutusScriptTag = \case
Spend -> LT.Spend
Mint -> LT.Mint
Cert -> LT.Cert
Reward -> LT.Reward
toCardanoAddress :: Blockfrost.Address -> Either String (C.AddressInEra C.BabbageEra)
toCardanoAddress bAddr = case deserialized of
Nothing -> Left "Error deserializing the Address"
Just des -> Right $ C.shelleyAddressInEra des
where
deserialized :: Maybe (Api.Address C.ShelleyAddr)
deserialized = C.deserialiseAddress C.AsShelleyAddress (unAddress bAddr)
credentialToAddress :: C.NetworkId -> Credential -> Blockfrost.Address
credentialToAddress netId c = case toCardanoAddressInEra netId pAddress of
Left err -> error $ show err
Right addr -> mkAddress $ C.serialiseAddress addr
where
pAddress :: LA.Address
pAddress = case c of
PubKeyCredential pkh -> LA.pubKeyHashAddress pkh
ScriptCredential valHash -> LA.scriptHashAddress valHash
txHashToTxId :: TxHash -> LT.TxId
txHashToTxId = LT.TxId .toBuiltin . fromJust . decodeHex . unTxHash
utxoToRef :: AddressUtxo -> TxOutRef
utxoToRef utxo = TxOutRef { txOutRefId=utxoToTxId utxo
, txOutRefIdx=_addressUtxoOutputIndex utxo
}
utxoToTxId :: AddressUtxo -> LT.TxId
utxoToTxId = txHashToTxId . _addressUtxoTxHash
txoToRef :: UtxoInput -> TxOutRef
txoToRef txo = TxOutRef { txOutRefId=txoToTxId txo
, txOutRefIdx=_utxoInputOutputIndex txo
}
We are forced to use blockfrost - client v0.3.1 by the cardano - wallet .
In that version , _ returns a Text instead of a TxHash
txoToTxId :: UtxoInput -> LT.TxId
txoToTxId = txHashToTxId . _utxoInputTxHash
amountsToValue :: [Blockfrost.Amount] -> C.Value
amountsToValue = foldMap blfAmountToValue
blfAmountToValue :: Blockfrost.Amount -> C.Value
blfAmountToValue amt = case amt of
AdaAmount lov -> lovelacesToValue lov
AssetAmount ds -> discreteCurrencyToValue ds
discreteCurrencyToValue :: Money.SomeDiscrete -> C.Value
discreteCurrencyToValue sd = Value.singleton pid an quant
where
pid :: C.PolicyId
pid = fromString $ unpack $ Text.take 56 $ someDiscreteCurrency sd
an :: C.AssetName
an = C.AssetName $ fromJust $ decodeHex $ Text.drop 56 $ someDiscreteCurrency sd
quant :: Integer
quant = someDiscreteAmount sd
lovelaceConfig :: Money.DecimalConf
lovelaceConfig = Money.defaultDecimalConf
{ Money.decimalConf_digits = 0
, Money.decimalConf_scale =
Money.scale (Proxy @(Money.UnitScale "ADA" "lovelace"))
}
lovelacesToMInt :: Lovelaces -> Maybe Integer
lovelacesToMInt = readMaybe . unpack . Money.discreteToDecimal lovelaceConfig Money.Round
lovelacesToValue :: Lovelaces -> C.Value
lovelacesToValue = Value.lovelaceValueOf . fromMaybe 0 . lovelacesToMInt
textToSlot :: Text -> Ledger.Slot
textToSlot = maybe (error "Failed to convert text to slot") Ledger.Slot . (readMaybe . unpack)
-- the functions "to", "from" and "interval" includes the parameters inside the validity range, meanwhile
blockfrost gives us an [ ) range , so we need to take one from the Right bound
toPlutusSlotRange :: Maybe Text -> Maybe Text -> Ledger.SlotRange
toPlutusSlotRange Nothing Nothing = always
toPlutusSlotRange Nothing (Just after) = to (textToSlot after - 1)
toPlutusSlotRange (Just before) Nothing = from (textToSlot before)
toPlutusSlotRange (Just before) (Just after) = interval (textToSlot before) (textToSlot after - 1)
| null | https://raw.githubusercontent.com/input-output-hk/plutus-apps/e8688b8f86a92b285e7d93eb418ccc314ad41bf9/pab-blockfrost/src/Plutus/Blockfrost/Utils.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE OverloadedStrings #
the functions "to", "from" and "interval" includes the parameters inside the validity range, meanwhile | # LANGUAGE DerivingStrategies #
# LANGUAGE LambdaCase #
# LANGUAGE TypeApplications #
module Plutus.Blockfrost.Utils where
import Data.Maybe (fromJust, fromMaybe)
import Data.Proxy (Proxy (..))
import Data.String
import Data.Text (Text, pack, unpack)
import Data.Text qualified as Text (drop, take)
import Text.Hex (decodeHex, encodeHex)
import Text.Read (readMaybe)
import Blockfrost.Client as Blockfrost
import Cardano.Api qualified as C
import Cardano.Api.Shelley qualified as Api
import Ledger.Slot qualified as Ledger (Slot (..), SlotRange)
import Ledger.Tx (TxOutRef (..))
import Ledger.Tx qualified as LT (ScriptTag (..), TxId (TxId))
import Ledger.Tx.CardanoAPI
import Ledger.Value.CardanoAPI qualified as Value
import Money (Approximation (Round), DecimalConf (..), SomeDiscrete, UnitScale, defaultDecimalConf, discreteToDecimal,
scale, someDiscreteAmount, someDiscreteCurrency)
import Plutus.V1.Ledger.Address qualified as LA
import Plutus.V1.Ledger.Api (Credential (..), fromBuiltin, toBuiltin, unCurrencySymbol, unTokenName)
import Plutus.V1.Ledger.Api qualified (DatumHash, RedeemerHash)
import Plutus.V1.Ledger.Interval (always, from, interval, to)
import Plutus.V1.Ledger.Scripts qualified as PS
import Plutus.V1.Ledger.Value (AssetClass, unAssetClass)
class Show a => ToBlockfrostScriptHash a where
toBlockfrostScriptHash :: a -> Blockfrost.ScriptHash
toBlockfrostScriptHash = fromString . show
instance ToBlockfrostScriptHash PS.ValidatorHash
instance ToBlockfrostScriptHash PS.MintingPolicyHash
instance ToBlockfrostScriptHash PS.StakeValidatorHash
class Show a => ToBlockfrostDatumHash a where
toBlockfrostDatumHash :: a -> Blockfrost.DatumHash
toBlockfrostDatumHash = fromString . show
instance ToBlockfrostDatumHash Plutus.V1.Ledger.Api.DatumHash
instance ToBlockfrostDatumHash Plutus.V1.Ledger.Api.RedeemerHash
toBlockfrostTxHash :: LT.TxId -> TxHash
toBlockfrostTxHash = TxHash . pack . show
toBlockfrostTxHashes :: [LT.TxId] -> [TxHash]
toBlockfrostTxHashes = map toBlockfrostTxHash
toBlockfrostRef :: TxOutRef -> (TxHash, Integer)
toBlockfrostRef ref = (toBlockfrostTxHash (txOutRefId ref), txOutRefIdx ref)
toBlockfrostAssetId :: AssetClass -> AssetId
toBlockfrostAssetId ac = fromString (polId ++ tName)
where
(cs, tn) = unAssetClass ac
polId :: String
polId = (unpack . encodeHex . fromBuiltin . unCurrencySymbol) cs
tName :: String
tName = (unpack . encodeHex . fromBuiltin . unTokenName) tn
textToDatumHash :: Text -> PS.DatumHash
textToDatumHash = PS.DatumHash . toBuiltin . fromJust . decodeHex
textToScriptHash :: Text -> PS.ScriptHash
textToScriptHash = PS.ScriptHash . toBuiltin . fromJust . decodeHex
textToRedeemerHash :: Text -> PS.RedeemerHash
textToRedeemerHash = PS.RedeemerHash . toBuiltin . fromJust . decodeHex
toPlutusScriptTag :: ValidationPurpose -> LT.ScriptTag
toPlutusScriptTag = \case
Spend -> LT.Spend
Mint -> LT.Mint
Cert -> LT.Cert
Reward -> LT.Reward
toCardanoAddress :: Blockfrost.Address -> Either String (C.AddressInEra C.BabbageEra)
toCardanoAddress bAddr = case deserialized of
Nothing -> Left "Error deserializing the Address"
Just des -> Right $ C.shelleyAddressInEra des
where
deserialized :: Maybe (Api.Address C.ShelleyAddr)
deserialized = C.deserialiseAddress C.AsShelleyAddress (unAddress bAddr)
credentialToAddress :: C.NetworkId -> Credential -> Blockfrost.Address
credentialToAddress netId c = case toCardanoAddressInEra netId pAddress of
Left err -> error $ show err
Right addr -> mkAddress $ C.serialiseAddress addr
where
pAddress :: LA.Address
pAddress = case c of
PubKeyCredential pkh -> LA.pubKeyHashAddress pkh
ScriptCredential valHash -> LA.scriptHashAddress valHash
txHashToTxId :: TxHash -> LT.TxId
txHashToTxId = LT.TxId .toBuiltin . fromJust . decodeHex . unTxHash
utxoToRef :: AddressUtxo -> TxOutRef
utxoToRef utxo = TxOutRef { txOutRefId=utxoToTxId utxo
, txOutRefIdx=_addressUtxoOutputIndex utxo
}
utxoToTxId :: AddressUtxo -> LT.TxId
utxoToTxId = txHashToTxId . _addressUtxoTxHash
txoToRef :: UtxoInput -> TxOutRef
txoToRef txo = TxOutRef { txOutRefId=txoToTxId txo
, txOutRefIdx=_utxoInputOutputIndex txo
}
We are forced to use blockfrost - client v0.3.1 by the cardano - wallet .
In that version , _ returns a Text instead of a TxHash
txoToTxId :: UtxoInput -> LT.TxId
txoToTxId = txHashToTxId . _utxoInputTxHash
amountsToValue :: [Blockfrost.Amount] -> C.Value
amountsToValue = foldMap blfAmountToValue
blfAmountToValue :: Blockfrost.Amount -> C.Value
blfAmountToValue amt = case amt of
AdaAmount lov -> lovelacesToValue lov
AssetAmount ds -> discreteCurrencyToValue ds
discreteCurrencyToValue :: Money.SomeDiscrete -> C.Value
discreteCurrencyToValue sd = Value.singleton pid an quant
where
pid :: C.PolicyId
pid = fromString $ unpack $ Text.take 56 $ someDiscreteCurrency sd
an :: C.AssetName
an = C.AssetName $ fromJust $ decodeHex $ Text.drop 56 $ someDiscreteCurrency sd
quant :: Integer
quant = someDiscreteAmount sd
lovelaceConfig :: Money.DecimalConf
lovelaceConfig = Money.defaultDecimalConf
{ Money.decimalConf_digits = 0
, Money.decimalConf_scale =
Money.scale (Proxy @(Money.UnitScale "ADA" "lovelace"))
}
lovelacesToMInt :: Lovelaces -> Maybe Integer
lovelacesToMInt = readMaybe . unpack . Money.discreteToDecimal lovelaceConfig Money.Round
lovelacesToValue :: Lovelaces -> C.Value
lovelacesToValue = Value.lovelaceValueOf . fromMaybe 0 . lovelacesToMInt
textToSlot :: Text -> Ledger.Slot
textToSlot = maybe (error "Failed to convert text to slot") Ledger.Slot . (readMaybe . unpack)
blockfrost gives us an [ ) range , so we need to take one from the Right bound
toPlutusSlotRange :: Maybe Text -> Maybe Text -> Ledger.SlotRange
toPlutusSlotRange Nothing Nothing = always
toPlutusSlotRange Nothing (Just after) = to (textToSlot after - 1)
toPlutusSlotRange (Just before) Nothing = from (textToSlot before)
toPlutusSlotRange (Just before) (Just after) = interval (textToSlot before) (textToSlot after - 1)
|
d88fcb9e41398dbd6905cdf66bb272897c6f1f2d3f97c520cb043c4a9bf080a6 | tact-lang/tact-obsolete | discriminator.ml | open Base
module Make =
functor
(Config : Config.T)
->
struct
open Lang_types.Make (Config)
module LocalDiscriminators = struct
type t = unit
open struct
let get_discr_from_attrs attrs =
List.find_map attrs ~f:(fun {attribute_ident; attribute_exprs} ->
match (attribute_ident.value, attribute_exprs) with
| "discriminator", [{value = Value (Integer x); _}] ->
Some (Discriminator {discr = Z.to_int x; bits = None})
| ( "discriminator",
[ {value = Value (Integer x); _};
{value = Value (Integer bits); _} ] ) ->
Some
(Discriminator
{discr = Z.to_int x; bits = Some (Z.to_int bits)} )
| _ ->
None )
end
let choose_discriminators :
t ->
int ->
(type_ * attribute list) list ->
(type_ * discriminator) list =
fun _ _ cases ->
List.mapi (List.rev cases) ~f:(fun id (case, attrs) ->
( case,
Option.value_or_thunk (get_discr_from_attrs attrs)
~default:(fun _ -> Discriminator {discr = id; bits = None}) ) )
|> List.rev
end
end
| null | https://raw.githubusercontent.com/tact-lang/tact-obsolete/3ae7046c654048ccc7c77db85fdf5e07df557a2f/lib/discriminator.ml | ocaml | open Base
module Make =
functor
(Config : Config.T)
->
struct
open Lang_types.Make (Config)
module LocalDiscriminators = struct
type t = unit
open struct
let get_discr_from_attrs attrs =
List.find_map attrs ~f:(fun {attribute_ident; attribute_exprs} ->
match (attribute_ident.value, attribute_exprs) with
| "discriminator", [{value = Value (Integer x); _}] ->
Some (Discriminator {discr = Z.to_int x; bits = None})
| ( "discriminator",
[ {value = Value (Integer x); _};
{value = Value (Integer bits); _} ] ) ->
Some
(Discriminator
{discr = Z.to_int x; bits = Some (Z.to_int bits)} )
| _ ->
None )
end
let choose_discriminators :
t ->
int ->
(type_ * attribute list) list ->
(type_ * discriminator) list =
fun _ _ cases ->
List.mapi (List.rev cases) ~f:(fun id (case, attrs) ->
( case,
Option.value_or_thunk (get_discr_from_attrs attrs)
~default:(fun _ -> Discriminator {discr = id; bits = None}) ) )
|> List.rev
end
end
| |
4fd28c06217a7166d5080d1937f66cc7e597935d11ca3b2751336e9d73069370 | gregr/experiments | map-map-cps.rkt | #lang racket
(define (map f xs)
(if (null? xs)
'()
(let ((a (f (car xs)))
(d (map f (cdr xs))))
(cons a d))))
(define (map/k k f xs)
(if (null? xs)
(k '())
(f (lambda (a)
(map/k (lambda (d) (k (cons a d)))
f (cdr xs)))
(car xs))))
(define (+1 x) (+ x 1))
(define (*2 x) (* x 2))
;;;;;;;;;;;;;;;;;;
;; direct style ;;
;;;;;;;;;;;;;;;;;;
(define (H Xs) (map +1 (map *2 Xs)))
(let ((Ys (map *2 Xs)))
(map +1 Ys))
(let ((Ys (if (null? Xs)
'()
(let ((A (*2 (car Xs)))
(D (map *2 (cdr Xs))))
(cons A D)))))
(map +1 Ys))
(if (null? Xs)
(map +1 '())
(let ((A (*2 (car Xs)))
(D (map *2 (cdr Xs))))
(map +1 (cons A D))))
(if (null? Xs)
'()
(let ((A (*2 (car Xs)))
(D (map *2 (cdr Xs)))) ;; *
(let ((AA (+1 A))
(DD (map +1 D)))
(cons AA DD))))
;; lower let binding to use site (safe to pass +1, which is pure)
(if (null? Xs)
'()
(let ((A (*2 (car Xs))))
(let ((AA (+1 A))
(DD (let ((D (map *2 (cdr Xs)))) ;; *
(map +1 D))))
(cons AA DD))))
(define (H Xs)
(if (null? Xs)
'()
(let ((A (*2 (car Xs))))
(let ((AA (+1 A))
(DD (H (cdr Xs))))
(cons AA DD)))))
(define (H Xs)
(if (null? Xs)
'()
(cons (+1 (*2 (car Xs))) (H (cdr Xs)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
cps ( assume direct style for primitives +1 * 2 for simplicity ) ; ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (H/k K Xs)
(map/k (lambda (Ys) (map/k K +1 Ys))
*2 Xs))
(map/k (lambda (Ys) (map/k K +1 Ys))
*2 Xs)
(if (null? Xs)
((lambda (Ys) (map/k K +1 Ys)) '())
(primcall *2 (lambda (A)
(map/k (lambda (D) ((lambda (Ys) (map/k K +1 Ys))
(cons A D)))
*2 (cdr Xs)))
(car Xs)))
(if (null? Xs)
(map/k K +1 '())
(let ((A (*2 (car Xs))))
(map/k (lambda (D) ((lambda (Ys) (map/k K +1 Ys))
(cons A D)))
*2 (cdr Xs))))
(if (null? Xs)
(K '())
(let ((A (*2 (car Xs))))
(map/k (lambda (D) (map/k K +1 (cons A D)))
*2 (cdr Xs))))
(if (null? Xs)
(K '())
(let ((A (*2 (car Xs))))
(map/k (lambda (D)
(primcall +1 (lambda (AA)
(map/k (lambda (DD) (K (cons AA DD)))
+1 D))
A))
*2 (cdr Xs))))
(if (null? Xs)
(K '())
(let ((A (*2 (car Xs))))
(map/k (lambda (D)
(let ((AA (+1 A))) ;; *
(map/k (lambda (DD) (K (cons AA DD)))
+1 D)))
*2 (cdr Xs))))
;; float pure binding
(if (null? Xs)
(K '())
(let ((A (*2 (car Xs))))
(let ((AA (+1 A))) ;; *
(map/k (lambda (D)
(map/k (lambda (DD) (K (cons AA DD)))
+1 D))
*2 (cdr Xs)))))
(if (null? Xs)
(K '())
(let ((A (*2 (car Xs))))
(let ((AA (+1 A)))
(H/k (lambda (DD) (K (cons AA DD)))
(cdr Xs)))))
(define (H/k K Xs)
(if (null? Xs)
(K '())
(let ((A (*2 (car Xs))))
(let ((AA (+1 A)))
(H/k (lambda (DD) (K (cons AA DD)))
(cdr Xs))))))
(define (H/k K Xs)
(if (null? Xs)
(K '())
(let ((AA (+1 (*2 (car Xs)))))
(H/k (lambda (DD) (K (cons AA DD)))
(cdr Xs)))))
| null | https://raw.githubusercontent.com/gregr/experiments/cd4c7953f45102539081077bbd6195cf834ba2fa/supercompilation/map-map-cps.rkt | racket |
direct style ;;
*
lower let binding to use site (safe to pass +1, which is pure)
*
;
*
float pure binding
* | #lang racket
(define (map f xs)
(if (null? xs)
'()
(let ((a (f (car xs)))
(d (map f (cdr xs))))
(cons a d))))
(define (map/k k f xs)
(if (null? xs)
(k '())
(f (lambda (a)
(map/k (lambda (d) (k (cons a d)))
f (cdr xs)))
(car xs))))
(define (+1 x) (+ x 1))
(define (*2 x) (* x 2))
(define (H Xs) (map +1 (map *2 Xs)))
(let ((Ys (map *2 Xs)))
(map +1 Ys))
(let ((Ys (if (null? Xs)
'()
(let ((A (*2 (car Xs)))
(D (map *2 (cdr Xs))))
(cons A D)))))
(map +1 Ys))
(if (null? Xs)
(map +1 '())
(let ((A (*2 (car Xs)))
(D (map *2 (cdr Xs))))
(map +1 (cons A D))))
(if (null? Xs)
'()
(let ((A (*2 (car Xs)))
(let ((AA (+1 A))
(DD (map +1 D)))
(cons AA DD))))
(if (null? Xs)
'()
(let ((A (*2 (car Xs))))
(let ((AA (+1 A))
(map +1 D))))
(cons AA DD))))
(define (H Xs)
(if (null? Xs)
'()
(let ((A (*2 (car Xs))))
(let ((AA (+1 A))
(DD (H (cdr Xs))))
(cons AA DD)))))
(define (H Xs)
(if (null? Xs)
'()
(cons (+1 (*2 (car Xs))) (H (cdr Xs)))))
(define (H/k K Xs)
(map/k (lambda (Ys) (map/k K +1 Ys))
*2 Xs))
(map/k (lambda (Ys) (map/k K +1 Ys))
*2 Xs)
(if (null? Xs)
((lambda (Ys) (map/k K +1 Ys)) '())
(primcall *2 (lambda (A)
(map/k (lambda (D) ((lambda (Ys) (map/k K +1 Ys))
(cons A D)))
*2 (cdr Xs)))
(car Xs)))
(if (null? Xs)
(map/k K +1 '())
(let ((A (*2 (car Xs))))
(map/k (lambda (D) ((lambda (Ys) (map/k K +1 Ys))
(cons A D)))
*2 (cdr Xs))))
(if (null? Xs)
(K '())
(let ((A (*2 (car Xs))))
(map/k (lambda (D) (map/k K +1 (cons A D)))
*2 (cdr Xs))))
(if (null? Xs)
(K '())
(let ((A (*2 (car Xs))))
(map/k (lambda (D)
(primcall +1 (lambda (AA)
(map/k (lambda (DD) (K (cons AA DD)))
+1 D))
A))
*2 (cdr Xs))))
(if (null? Xs)
(K '())
(let ((A (*2 (car Xs))))
(map/k (lambda (D)
(map/k (lambda (DD) (K (cons AA DD)))
+1 D)))
*2 (cdr Xs))))
(if (null? Xs)
(K '())
(let ((A (*2 (car Xs))))
(map/k (lambda (D)
(map/k (lambda (DD) (K (cons AA DD)))
+1 D))
*2 (cdr Xs)))))
(if (null? Xs)
(K '())
(let ((A (*2 (car Xs))))
(let ((AA (+1 A)))
(H/k (lambda (DD) (K (cons AA DD)))
(cdr Xs)))))
(define (H/k K Xs)
(if (null? Xs)
(K '())
(let ((A (*2 (car Xs))))
(let ((AA (+1 A)))
(H/k (lambda (DD) (K (cons AA DD)))
(cdr Xs))))))
(define (H/k K Xs)
(if (null? Xs)
(K '())
(let ((AA (+1 (*2 (car Xs)))))
(H/k (lambda (DD) (K (cons AA DD)))
(cdr Xs)))))
|
bc514d83de1783e88fce41e9a6202496e99ce8671351b5ba6489d5245bba519f | halgari/naiad | nodes.clj | (ns naiad.nodes
(:require [clojure.core :as clj]
[naiad.graph :refer [add-node! gen-id id? *graph* ports
INode]]
[naiad.backends.csp :as csp]
[clojure.core.async :refer [go <! >! close! thread] :as async]))
(defmacro process [{:keys [blocking-io] :as opts} & body]
(if blocking-io
`(thread)))
(defmethod csp/construct! :naiad/map
[{:keys [inputs outputs f]}]
(go
(let [out (:out outputs)]
(loop [acc []]
(if (< (count acc) (count inputs))
(if-some [v (<! (inputs (count acc)))]
(recur (conj acc v))
(do (close! out)
(doseq [[k v] inputs]
(close! v))))
(if (>! out (apply f acc))
(recur [])
(doseq [[_ v] inputs]
(close! v))))))))
(defmacro gen-transducer-node [f]
`(fn ~f [& args#]
(let [fargs# (butlast args#)
input# (last args#)
output# (gen-id)]
(add-node!
{:type :generic-transducer
:f (apply ~f fargs#)
:transducer? true
:inputs {:in input#}
:outputs {:out output#}})
output#)))
(defmacro gen-verbose-transducer-node [f arg-names]
(let [fname (symbol (str (name f) "-node"))]
`(let [extractor# (apply juxt ~arg-names)]
(fn ~fname
([first# & rargs#]
(~fname (apply hash-map first# rargs#)))
([args#]
(let [fargs# (extractor# args#)
input# (or (:in args#) (gen-id))
output# (or (:out args#) (gen-id))]
(add-node!
{:type :generic-transducer
:f (apply ~f fargs#)
:transducer? true
:inputs {:in input#}
:outputs {:out output#}})
output#))))))
(defn map-keys [mp from to]
(if-let [v (get mp from)]
(assoc-in (dissoc mp from) to v)
mp))
(defmethod csp/construct! :naiad/promise-accumulator
[{:keys [inputs promise]}]
(async/take! (async/into [] (:in inputs))
(partial deliver promise)))
(defmethod csp/construct! :naiad/duplicate
[{:keys [inputs outputs]}]
(let [in (:in inputs)
outs (vec (vals outputs))]
(go (loop []
(if-some [v (<! in)]
(let [exit? (loop [remain (set (map #(vector % v) outs))]
(when (> (count remain) 0)
(let [[ret c] (async/alts! (vec remain))]
(if ret
(recur (disj remain [c v]))
(do (doseq [c outs]
(close! c))
(close! in)
:exit)))))]
(when-not exit?
(recur)))
(doseq [c outs]
(close! c)))))))
(defmethod csp/construct! :naiad/merge
[{:keys [inputs outputs]}]
(let [ins (vals inputs)
out (:out outputs)]
(go (loop [ins ins]
(when (pos? (count ins))
(let [[v c] (async/alts! ins)]
(if v
(if (>! out v)
(recur ins)
(do (doseq [in ins]
(close! ins))))
(do (close! c)
(recur (remove (partial = c) ins)))))))
(close! out))))
(defmethod csp/construct! :naiad/subscribe
[{:keys [topic-fn inputs outputs default-key default-c]}]
(let [default-c (or (and default-key (default-key outputs))
default-c)
in-c (:in inputs)]
(go
(loop []
(if-some [v (<! in-c)]
(let [topic (topic-fn v)
out-c (or (outputs topic)
default-c)]
(if out-c
(if (>! out-c v)
(recur)
(do (close! in-c)
(doseq [[k v] outputs]
(close! v))))
(recur)))
(do (doseq [[k v] outputs]
(close! v))))))))
(defmethod csp/construct! :naiad/onto-chan
[{:keys [outputs coll]}]
(clojure.core.async/onto-chan (:out outputs) coll true))
(defmethod csp/construct! :naiad/no-close
[{:keys [inputs outputs]}]
(clojure.core.async/pipe (:in inputs) (:out outputs) false))
(defn close-all!
([& chans-seq]
(doseq [chans chans-seq]
(doseq [c (if (map? chans)
(vals chans)
chans)]
(close! c)))))
(defn index-of [coll itm]
(loop [idx 0
s (seq coll)]
(if s
(if (= (first s) itm)
idx
(recur (inc idx) (next s)))
nil)))
(defmethod csp/construct! :naiad/multiplexer
[{:keys [inputs outputs]}]
(let [out (:out outputs)
selector (:selector inputs)
closed-c (let [c (async/chan)]
(close! c)
c)]
(go (loop []
(if-some [idx (<! selector)]
(if-some [v (<! (get inputs idx closed-c))]
(if (>! out v)
(recur)
(close-all! inputs outputs))
(recur))
(close-all! inputs outputs))))))
(defmethod csp/construct! :naiad/demultiplexer
[{:keys [inputs outputs]}]
(let [selector (:selector outputs)
in (:in inputs)
outs (vals (dissoc outputs :selector))]
(go (loop []
(if-some [v (<! in)]
(let [[v c] (async/alts! (map vector outs (repeat v)))
idx (index-of outs c)]
(if v
(if (>! selector idx)
(recur)
(close-all! inputs outputs))
(close-all! inputs outputs)))
(close-all! inputs outputs))))))
(defmethod csp/construct! :naiad/mapcat-async
[{:keys [inputs outputs f] :as node}]
(go
(let [out (:out outputs)]
(loop [acc []]
(if (< (count acc) (count inputs))
(if-some [v (<! (inputs (count acc)))]
(recur (conj acc v))
(close-all! inputs outputs))
(let [continue? (let [c (async/chan 1)]
(apply f c acc)
(loop []
(if-some [v (<! c)]
(if (>! out v)
(recur)
false)
true)))]
(if continue?
(recur [])
(close-all! inputs outputs)))))))) | null | https://raw.githubusercontent.com/halgari/naiad/c47bc6f9d2e8e4222bd7820fa404d9ceebfc8e22/src/naiad/nodes.clj | clojure | (ns naiad.nodes
(:require [clojure.core :as clj]
[naiad.graph :refer [add-node! gen-id id? *graph* ports
INode]]
[naiad.backends.csp :as csp]
[clojure.core.async :refer [go <! >! close! thread] :as async]))
(defmacro process [{:keys [blocking-io] :as opts} & body]
(if blocking-io
`(thread)))
(defmethod csp/construct! :naiad/map
[{:keys [inputs outputs f]}]
(go
(let [out (:out outputs)]
(loop [acc []]
(if (< (count acc) (count inputs))
(if-some [v (<! (inputs (count acc)))]
(recur (conj acc v))
(do (close! out)
(doseq [[k v] inputs]
(close! v))))
(if (>! out (apply f acc))
(recur [])
(doseq [[_ v] inputs]
(close! v))))))))
(defmacro gen-transducer-node [f]
`(fn ~f [& args#]
(let [fargs# (butlast args#)
input# (last args#)
output# (gen-id)]
(add-node!
{:type :generic-transducer
:f (apply ~f fargs#)
:transducer? true
:inputs {:in input#}
:outputs {:out output#}})
output#)))
(defmacro gen-verbose-transducer-node [f arg-names]
(let [fname (symbol (str (name f) "-node"))]
`(let [extractor# (apply juxt ~arg-names)]
(fn ~fname
([first# & rargs#]
(~fname (apply hash-map first# rargs#)))
([args#]
(let [fargs# (extractor# args#)
input# (or (:in args#) (gen-id))
output# (or (:out args#) (gen-id))]
(add-node!
{:type :generic-transducer
:f (apply ~f fargs#)
:transducer? true
:inputs {:in input#}
:outputs {:out output#}})
output#))))))
(defn map-keys [mp from to]
(if-let [v (get mp from)]
(assoc-in (dissoc mp from) to v)
mp))
(defmethod csp/construct! :naiad/promise-accumulator
[{:keys [inputs promise]}]
(async/take! (async/into [] (:in inputs))
(partial deliver promise)))
(defmethod csp/construct! :naiad/duplicate
[{:keys [inputs outputs]}]
(let [in (:in inputs)
outs (vec (vals outputs))]
(go (loop []
(if-some [v (<! in)]
(let [exit? (loop [remain (set (map #(vector % v) outs))]
(when (> (count remain) 0)
(let [[ret c] (async/alts! (vec remain))]
(if ret
(recur (disj remain [c v]))
(do (doseq [c outs]
(close! c))
(close! in)
:exit)))))]
(when-not exit?
(recur)))
(doseq [c outs]
(close! c)))))))
(defmethod csp/construct! :naiad/merge
[{:keys [inputs outputs]}]
(let [ins (vals inputs)
out (:out outputs)]
(go (loop [ins ins]
(when (pos? (count ins))
(let [[v c] (async/alts! ins)]
(if v
(if (>! out v)
(recur ins)
(do (doseq [in ins]
(close! ins))))
(do (close! c)
(recur (remove (partial = c) ins)))))))
(close! out))))
(defmethod csp/construct! :naiad/subscribe
[{:keys [topic-fn inputs outputs default-key default-c]}]
(let [default-c (or (and default-key (default-key outputs))
default-c)
in-c (:in inputs)]
(go
(loop []
(if-some [v (<! in-c)]
(let [topic (topic-fn v)
out-c (or (outputs topic)
default-c)]
(if out-c
(if (>! out-c v)
(recur)
(do (close! in-c)
(doseq [[k v] outputs]
(close! v))))
(recur)))
(do (doseq [[k v] outputs]
(close! v))))))))
(defmethod csp/construct! :naiad/onto-chan
[{:keys [outputs coll]}]
(clojure.core.async/onto-chan (:out outputs) coll true))
(defmethod csp/construct! :naiad/no-close
[{:keys [inputs outputs]}]
(clojure.core.async/pipe (:in inputs) (:out outputs) false))
(defn close-all!
([& chans-seq]
(doseq [chans chans-seq]
(doseq [c (if (map? chans)
(vals chans)
chans)]
(close! c)))))
(defn index-of [coll itm]
(loop [idx 0
s (seq coll)]
(if s
(if (= (first s) itm)
idx
(recur (inc idx) (next s)))
nil)))
(defmethod csp/construct! :naiad/multiplexer
[{:keys [inputs outputs]}]
(let [out (:out outputs)
selector (:selector inputs)
closed-c (let [c (async/chan)]
(close! c)
c)]
(go (loop []
(if-some [idx (<! selector)]
(if-some [v (<! (get inputs idx closed-c))]
(if (>! out v)
(recur)
(close-all! inputs outputs))
(recur))
(close-all! inputs outputs))))))
(defmethod csp/construct! :naiad/demultiplexer
[{:keys [inputs outputs]}]
(let [selector (:selector outputs)
in (:in inputs)
outs (vals (dissoc outputs :selector))]
(go (loop []
(if-some [v (<! in)]
(let [[v c] (async/alts! (map vector outs (repeat v)))
idx (index-of outs c)]
(if v
(if (>! selector idx)
(recur)
(close-all! inputs outputs))
(close-all! inputs outputs)))
(close-all! inputs outputs))))))
(defmethod csp/construct! :naiad/mapcat-async
[{:keys [inputs outputs f] :as node}]
(go
(let [out (:out outputs)]
(loop [acc []]
(if (< (count acc) (count inputs))
(if-some [v (<! (inputs (count acc)))]
(recur (conj acc v))
(close-all! inputs outputs))
(let [continue? (let [c (async/chan 1)]
(apply f c acc)
(loop []
(if-some [v (<! c)]
(if (>! out v)
(recur)
false)
true)))]
(if continue?
(recur [])
(close-all! inputs outputs)))))))) | |
b546a3816c933bbd41517851bf69731f04470eaa1c27815360b43818934fe7f5 | ryanpbrewster/haskell | P099.hs | module TestData.P099 (txt) where
txt =
unlines
[ "519432 525806"
, "632382 518061"
, "78864 613712"
, "466580 530130"
, "780495 510032"
, "525895 525320"
, "15991 714883"
, "960290 502358"
, "760018 511029"
, "166800 575487"
, "210884 564478"
, "555151 523163"
, "681146 515199"
, "563395 522587"
, "738250 512126"
, "923525 503780"
, "595148 520429"
, "177108 572629"
, "750923 511482"
, "440902 532446"
, "881418 505504"
, "422489 534197"
, "979858 501616"
, "685893 514935"
, "747477 511661"
, "167214 575367"
, "234140 559696"
, "940238 503122"
, "728969 512609"
, "232083 560102"
, "900971 504694"
, "688801 514772"
, "189664 569402"
, "891022 505104"
, "445689 531996"
, "119570 591871"
, "821453 508118"
, "371084 539600"
, "911745 504251"
, "623655 518600"
, "144361 582486"
, "352442 541775"
, "420726 534367"
, "295298 549387"
, "6530 787777"
, "468397 529976"
, "672336 515696"
, "431861 533289"
, "84228 610150"
, "805376 508857"
, "444409 532117"
, "33833 663511"
, "381850 538396"
, "402931 536157"
, "92901 604930"
, "304825 548004"
, "731917 512452"
, "753734 511344"
, "51894 637373"
, "151578 580103"
, "295075 549421"
, "303590 548183"
, "333594 544123"
, "683952 515042"
, "60090 628880"
, "951420 502692"
, "28335 674991"
, "714940 513349"
, "343858 542826"
, "549279 523586"
, "804571 508887"
, "260653 554881"
, "291399 549966"
, "402342 536213"
, "408889 535550"
, "40328 652524"
, "375856 539061"
, "768907 510590"
, "165993 575715"
, "976327 501755"
, "898500 504795"
, "360404 540830"
, "478714 529095"
, "694144 514472"
, "488726 528258"
, "841380 507226"
, "328012 544839"
, "22389 690868"
, "604053 519852"
, "329514 544641"
, "772965 510390"
, "492798 527927"
, "30125 670983"
, "895603 504906"
, "450785 531539"
, "840237 507276"
, "380711 538522"
, "63577 625673"
, "76801 615157"
, "502694 527123"
, "597706 520257"
, "310484 547206"
, "944468 502959"
, "121283 591152"
, "451131 531507"
, "566499 522367"
, "425373 533918"
, "40240 652665"
, "39130 654392"
, "714926 513355"
, "469219 529903"
, "806929 508783"
, "287970 550487"
, "92189 605332"
, "103841 599094"
, "671839 515725"
, "452048 531421"
, "987837 501323"
, "935192 503321"
, "88585 607450"
, "613883 519216"
, "144551 582413"
, "647359 517155"
, "213902 563816"
, "184120 570789"
, "258126 555322"
, "502546 527130"
, "407655 535678"
, "401528 536306"
, "477490 529193"
, "841085 507237"
, "732831 512408"
, "833000 507595"
, "904694 504542"
, "581435 521348"
, "455545 531110"
, "873558 505829"
, "94916 603796"
, "720176 513068"
, "545034 523891"
, "246348 557409"
, "556452 523079"
, "832015 507634"
, "173663 573564"
, "502634 527125"
, "250732 556611"
, "569786 522139"
, "216919 563178"
, "521815 525623"
, "92304 605270"
, "164446 576167"
, "753413 511364"
, "11410 740712"
, "448845 531712"
, "925072 503725"
, "564888 522477"
, "7062 780812"
, "641155 517535"
, "738878 512100"
, "636204 517828"
, "372540 539436"
, "443162 532237"
, "571192 522042"
, "655350 516680"
, "299741 548735"
, "581914 521307"
, "965471 502156"
, "513441 526277"
, "808682 508700"
, "237589 559034"
, "543300 524025"
, "804712 508889"
, "247511 557192"
, "543486 524008"
, "504383 526992"
, "326529 545039"
, "792493 509458"
, "86033 609017"
, "126554 589005"
, "579379 521481"
, "948026 502823"
, "404777 535969"
, "265767 554022"
, "266876 553840"
, "46631 643714"
, "492397 527958"
, "856106 506581"
, "795757 509305"
, "748946 511584"
, "294694 549480"
, "409781 535463"
, "775887 510253"
, "543747 523991"
, "210592 564536"
, "517119 525990"
, "520253 525751"
, "247926 557124"
, "592141 520626"
, "346580 542492"
, "544969 523902"
, "506501 526817"
, "244520 557738"
, "144745 582349"
, "69274 620858"
, "292620 549784"
, "926027 503687"
, "736320 512225"
, "515528 526113"
, "407549 535688"
, "848089 506927"
, "24141 685711"
, "9224 757964"
, "980684 501586"
, "175259 573121"
, "489160 528216"
, "878970 505604"
, "969546 502002"
, "525207 525365"
, "690461 514675"
, "156510 578551"
, "659778 516426"
, "468739 529945"
, "765252 510770"
, "76703 615230"
, "165151 575959"
, "29779 671736"
, "928865 503569"
, "577538 521605"
, "927555 503618"
, "185377 570477"
, "974756 501809"
, "800130 509093"
, "217016 563153"
, "365709 540216"
, "774508 510320"
, "588716 520851"
, "631673 518104"
, "954076 502590"
, "777828 510161"
, "990659 501222"
, "597799 520254"
, "786905 509727"
, "512547 526348"
, "756449 511212"
, "869787 505988"
, "653747 516779"
, "84623 609900"
, "839698 507295"
, "30159 670909"
, "797275 509234"
, "678136 515373"
, "897144 504851"
, "989554 501263"
, "413292 535106"
, "55297 633667"
, "788650 509637"
, "486748 528417"
, "150724 580377"
, "56434 632490"
, "77207 614869"
, "588631 520859"
, "611619 519367"
, "100006 601055"
, "528924 525093"
, "190225 569257"
, "851155 506789"
, "682593 515114"
, "613043 519275"
, "514673 526183"
, "877634 505655"
, "878905 505602"
, "1926 914951"
, "613245 519259"
, "152481 579816"
, "841774 507203"
, "71060 619442"
, "865335 506175"
, "90244 606469"
, "302156 548388"
, "399059 536557"
, "478465 529113"
, "558601 522925"
, "69132 620966"
, "267663 553700"
, "988276 501310"
, "378354 538787"
, "529909 525014"
, "161733 576968"
, "758541 511109"
, "823425 508024"
, "149821 580667"
, "269258 553438"
, "481152 528891"
, "120871 591322"
, "972322 501901"
, "981350 501567"
, "676129 515483"
, "950860 502717"
, "119000 592114"
, "392252 537272"
, "191618 568919"
, "946699 502874"
, "289555 550247"
, "799322 509139"
, "703886 513942"
, "194812 568143"
, "261823 554685"
, "203052 566221"
, "217330 563093"
, "734748 512313"
, "391759 537328"
, "807052 508777"
, "564467 522510"
, "59186 629748"
, "113447 594545"
, "518063 525916"
, "905944 504492"
, "613922 519213"
, "439093 532607"
, "445946 531981"
, "230530 560399"
, "297887 549007"
, "459029 530797"
, "403692 536075"
, "855118 506616"
, "963127 502245"
, "841711 507208"
, "407411 535699"
, "924729 503735"
, "914823 504132"
, "333725 544101"
, "176345 572832"
, "912507 504225"
, "411273 535308"
, "259774 555036"
, "632853 518038"
, "119723 591801"
, "163902 576321"
, "22691 689944"
, "402427 536212"
, "175769 572988"
, "837260 507402"
, "603432 519893"
, "313679 546767"
, "538165 524394"
, "549026 523608"
, "61083 627945"
, "898345 504798"
, "992556 501153"
, "369999 539727"
, "32847 665404"
, "891292 505088"
, "152715 579732"
, "824104 507997"
, "234057 559711"
, "730507 512532"
, "960529 502340"
, "388395 537687"
, "958170 502437"
, "57105 631806"
, "186025 570311"
, "993043 501133"
, "576770 521664"
, "215319 563513"
, "927342 503628"
, "521353 525666"
, "39563 653705"
, "752516 511408"
, "110755 595770"
, "309749 547305"
, "374379 539224"
, "919184 503952"
, "990652 501226"
, "647780 517135"
, "187177 570017"
, "168938 574877"
, "649558 517023"
, "278126 552016"
, "162039 576868"
, "658512 516499"
, "498115 527486"
, "896583 504868"
, "561170 522740"
, "747772 511647"
, "775093 510294"
, "652081 516882"
, "724905 512824"
, "499707 527365"
, "47388 642755"
, "646668 517204"
, "571700 522007"
, "180430 571747"
, "710015 513617"
, "435522 532941"
, "98137 602041"
, "759176 511070"
, "486124 528467"
, "526942 525236"
, "878921 505604"
, "408313 535602"
, "926980 503640"
, "882353 505459"
, "566887 522345"
, "3326 853312"
, "911981 504248"
, "416309 534800"
, "392991 537199"
, "622829 518651"
, "148647 581055"
, "496483 527624"
, "666314 516044"
, "48562 641293"
, "672618 515684"
, "443676 532187"
, "274065 552661"
, "265386 554079"
, "347668 542358"
, "31816 667448"
, "181575 571446"
, "961289 502320"
, "365689 540214"
, "987950 501317"
, "932299 503440"
, "27388 677243"
, "746701 511701"
, "492258 527969"
, "147823 581323"
, "57918 630985"
, "838849 507333"
, "678038 515375"
, "27852 676130"
, "850241 506828"
, "818403 508253"
, "131717 587014"
, "850216 506834"
, "904848 504529"
, "189758 569380"
, "392845 537217"
, "470876 529761"
, "925353 503711"
, "285431 550877"
, "454098 531234"
, "823910 508003"
, "318493 546112"
, "766067 510730"
, "261277 554775"
, "421530 534289"
, "694130 514478"
, "120439 591498"
, "213308 563949"
, "854063 506662"
, "365255 540263"
, "165437 575872"
, "662240 516281"
, "289970 550181"
, "847977 506933"
, "546083 523816"
, "413252 535113"
, "975829 501767"
, "361540 540701"
, "235522 559435"
, "224643 561577"
, "736350 512229"
, "328303 544808"
, "35022 661330"
, "307838 547578"
, "474366 529458"
, "873755 505819"
, "73978 617220"
, "827387 507845"
, "670830 515791"
, "326511 545034"
, "309909 547285"
, "400970 536363"
, "884827 505352"
, "718307 513175"
, "28462 674699"
, "599384 520150"
, "253565 556111"
, "284009 551093"
, "343403 542876"
, "446557 531921"
, "992372 501160"
, "961601 502308"
, "696629 514342"
, "919537 503945"
, "894709 504944"
, "892201 505051"
, "358160 541097"
, "448503 531745"
, "832156 507636"
, "920045 503924"
, "926137 503675"
, "416754 534757"
, "254422 555966"
, "92498 605151"
, "826833 507873"
, "660716 516371"
, "689335 514746"
, "160045 577467"
, "814642 508425"
, "969939 501993"
, "242856 558047"
, "76302 615517"
, "472083 529653"
, "587101 520964"
, "99066 601543"
, "498005 527503"
, "709800 513624"
, "708000 513716"
, "20171 698134"
, "285020 550936"
, "266564 553891"
, "981563 501557"
, "846502 506991"
, "334 1190800"
, "209268 564829"
, "9844 752610"
, "996519 501007"
, "410059 535426"
, "432931 533188"
, "848012 506929"
, "966803 502110"
, "983434 501486"
, "160700 577267"
, "504374 526989"
, "832061 507640"
, "392825 537214"
, "443842 532165"
, "440352 532492"
, "745125 511776"
, "13718 726392"
, "661753 516312"
, "70500 619875"
, "436952 532814"
, "424724 533973"
, "21954 692224"
, "262490 554567"
, "716622 513264"
, "907584 504425"
, "60086 628882"
, "837123 507412"
, "971345 501940"
, "947162 502855"
, "139920 584021"
, "68330 621624"
, "666452 516038"
, "731446 512481"
, "953350 502619"
, "183157 571042"
, "845400 507045"
, "651548 516910"
, "20399 697344"
, "861779 506331"
, "629771 518229"
, "801706 509026"
, "189207 569512"
, "737501 512168"
, "719272 513115"
, "479285 529045"
, "136046 585401"
, "896746 504860"
, "891735 505067"
, "684771 514999"
, "865309 506184"
, "379066 538702"
, "503117 527090"
, "621780 518717"
, "209518 564775"
, "677135 515423"
, "987500 501340"
, "197049 567613"
, "329315 544673"
, "236756 559196"
, "357092 541226"
, "520440 525733"
, "213471 563911"
, "956852 502490"
, "702223 514032"
, "404943 535955"
, "178880 572152"
, "689477 514734"
, "691351 514630"
, "866669 506128"
, "370561 539656"
, "739805 512051"
, "71060 619441"
, "624861 518534"
, "261660 554714"
, "366137 540160"
, "166054 575698"
, "601878 519990"
, "153445 579501"
, "279899 551729"
, "379166 538691"
, "423209 534125"
, "675310 515526"
, "145641 582050"
, "691353 514627"
, "917468 504026"
, "284778 550976"
, "81040 612235"
, "161699 576978"
, "616394 519057"
, "767490 510661"
, "156896 578431"
, "427408 533714"
, "254849 555884"
, "737217 512182"
, "897133 504851"
, "203815 566051"
, "270822 553189"
, "135854 585475"
, "778805 510111"
, "784373 509847"
, "305426 547921"
, "733418 512375"
, "732087 512448"
, "540668 524215"
, "702898 513996"
, "628057 518328"
, "640280 517587"
, "422405 534204"
, "10604 746569"
, "746038 511733"
, "839808 507293"
, "457417 530938"
, "479030 529064"
, "341758 543090"
, "620223 518824"
, "251661 556451"
, "561790 522696"
, "497733 527521"
, "724201 512863"
, "489217 528217"
, "415623 534867"
, "624610 518548"
, "847541 506953"
, "432295 533249"
, "400391 536421"
, "961158 502319"
, "139173 584284"
, "421225 534315"
, "579083 521501"
, "74274 617000"
, "701142 514087"
, "374465 539219"
, "217814 562985"
, "358972 540995"
, "88629 607424"
, "288597 550389"
, "285819 550812"
, "538400 524385"
, "809930 508645"
, "738326 512126"
, "955461 502535"
, "163829 576343"
, "826475 507891"
, "376488 538987"
, "102234 599905"
, "114650 594002"
, "52815 636341"
, "434037 533082"
, "804744 508880"
, "98385 601905"
, "856620 506559"
, "220057 562517"
, "844734 507078"
, "150677 580387"
, "558697 522917"
, "621751 518719"
, "207067 565321"
, "135297 585677"
, "932968 503404"
, "604456 519822"
, "579728 521462"
, "244138 557813"
, "706487 513800"
, "711627 513523"
, "853833 506674"
, "497220 527562"
, "59428 629511"
, "564845 522486"
, "623621 518603"
, "242689 558077"
, "125091 589591"
, "363819 540432"
, "686453 514901"
, "656813 516594"
, "489901 528155"
, "386380 537905"
, "542819 524052"
, "243987 557841"
, "693412 514514"
, "488484 528271"
, "896331 504881"
, "336730 543721"
, "728298 512647"
, "604215 519840"
, "153729 579413"
, "595687 520398"
, "540360 524240"
, "245779 557511"
, "924873 503730"
, "509628 526577"
, "528523 525122"
, "3509 847707"
, "522756 525555"
, "895447 504922"
, "44840 646067"
, "45860 644715"
, "463487 530404"
, "398164 536654"
, "894483 504959"
, "619415 518874"
, "966306 502129"
, "990922 501212"
, "835756 507474"
, "548881 523618"
, "453578 531282"
, "474993 529410"
, "80085 612879"
, "737091 512193"
, "50789 638638"
, "979768 501620"
, "792018 509483"
, "665001 516122"
, "86552 608694"
, "462772 530469"
, "589233 520821"
, "891694 505072"
, "592605 520594"
, "209645 564741"
, "42531 649269"
, "554376 523226"
, "803814 508929"
, "334157 544042"
, "175836 572970"
, "868379 506051"
, "658166 516520"
, "278203 551995"
, "966198 502126"
, "627162 518387"
, "296774 549165"
, "311803 547027"
, "843797 507118"
, "702304 514032"
, "563875 522553"
, "33103 664910"
, "191932 568841"
, "543514 524006"
, "506835 526794"
, "868368 506052"
, "847025 506971"
, "678623 515342"
, "876139 505726"
, "571997 521984"
, "598632 520198"
, "213590 563892"
, "625404 518497"
, "726508 512738"
, "689426 514738"
, "332495 544264"
, "411366 535302"
, "242546 558110"
, "315209 546555"
, "797544 509219"
, "93889 604371"
, "858879 506454"
, "124906 589666"
, "449072 531693"
, "235960 559345"
, "642403 517454"
, "720567 513047"
, "705534 513858"
, "603692 519870"
, "488137 528302"
, "157370 578285"
, "63515 625730"
, "666326 516041"
, "619226 518883"
, "443613 532186"
, "597717 520257"
, "96225 603069"
, "86940 608450"
, "40725 651929"
, "460976 530625"
, "268875 553508"
, "270671 553214"
, "363254 540500"
, "384248 538137"
, "762889 510892"
, "377941 538833"
, "278878 551890"
, "176615 572755"
, "860008 506412"
, "944392 502967"
, "608395 519571"
, "225283 561450"
, "45095 645728"
, "333798 544090"
, "625733 518476"
, "995584 501037"
, "506135 526853"
, "238050 558952"
, "557943 522972"
, "530978 524938"
, "634244 517949"
, "177168 572616"
, "85200 609541"
, "953043 502630"
, "523661 525484"
, "999295 500902"
, "840803 507246"
, "961490 502312"
, "471747 529685"
, "380705 538523"
, "911180 504275"
, "334149 544046"
, "478992 529065"
, "325789 545133"
, "335884 543826"
, "426976 533760"
, "749007 511582"
, "667067 516000"
, "607586 519623"
, "674054 515599"
, "188534 569675"
, "565185 522464"
, "172090 573988"
, "87592 608052"
, "907432 504424"
, "8912 760841"
, "928318 503590"
, "757917 511138"
, "718693 513153"
, "315141 546566"
, "728326 512645"
, "353492 541647"
, "638429 517695"
, "628892 518280"
, "877286 505672"
, "620895 518778"
, "385878 537959"
, "423311 534113"
, "633501 517997"
, "884833 505360"
, "883402 505416"
, "999665 500894"
, "708395 513697"
, "548142 523667"
, "756491 511205"
, "987352 501340"
, "766520 510705"
, "591775 520647"
, "833758 507563"
, "843890 507108"
, "925551 503698"
, "74816 616598"
, "646942 517187"
, "354923 541481"
, "256291 555638"
, "634470 517942"
, "930904 503494"
, "134221 586071"
, "282663 551304"
, "986070 501394"
, "123636 590176"
, "123678 590164"
, "481717 528841"
, "423076 534137"
, "866246 506145"
, "93313 604697"
, "783632 509880"
, "317066 546304"
, "502977 527103"
, "141272 583545"
, "71708 618938"
, "617748 518975"
, "581190 521362"
, "193824 568382"
, "682368 515131"
, "352956 541712"
, "351375 541905"
, "505362 526909"
, "905165 504518"
, "128645 588188"
, "267143 553787"
, "158409 577965"
, "482776 528754"
, "628896 518282"
, "485233 528547"
, "563606 522574"
, "111001 595655"
, "115920 593445"
, "365510 540237"
, "959724 502374"
, "938763 503184"
, "930044 503520"
, "970959 501956"
, "913658 504176"
, "68117 621790"
, "989729 501253"
, "567697 522288"
, "820427 508163"
, "54236 634794"
, "291557 549938"
, "124961 589646"
, "403177 536130"
, "405421 535899"
, "410233 535417"
, "815111 508403"
, "213176 563974"
, "83099 610879"
, "998588 500934"
, "513640 526263"
, "129817 587733"
, "1820 921851"
, "287584 550539"
, "299160 548820"
, "860621 506386"
, "529258 525059"
, "586297 521017"
, "953406 502616"
, "441234 532410"
, "986217 501386"
, "781938 509957"
, "461247 530595"
, "735424 512277"
, "146623 581722"
, "839838 507288"
, "510667 526494"
, "935085 503327"
, "737523 512167"
, "303455 548204"
, "992779 501145"
, "60240 628739"
, "939095 503174"
, "794368 509370"
, "501825 527189"
, "459028 530798"
, "884641 505363"
, "512287 526364"
, "835165 507499"
, "307723 547590"
, "160587 577304"
, "735043 512300"
, "493289 527887"
, "110717 595785"
, "306480 547772"
, "318593 546089"
, "179810 571911"
, "200531 566799"
, "314999 546580"
, "197020 567622"
, "301465 548487"
, "237808 559000"
, "131944 586923"
, "882527 505449"
, "468117 530003"
, "711319 513541"
, "156240 578628"
, "965452 502162"
, "992756 501148"
, "437959 532715"
, "739938 512046"
, "614249 519196"
, "391496 537356"
, "62746 626418"
, "688215 514806"
, "75501 616091"
, "883573 505412"
, "558824 522910"
, "759371 511061"
, "173913 573489"
, "891351 505089"
, "727464 512693"
, "164833 576051"
, "812317 508529"
, "540320 524243"
, "698061 514257"
, "69149 620952"
, "471673 529694"
, "159092 577753"
, "428134 533653"
, "89997 606608"
, "711061 513557"
, "779403 510081"
, "203327 566155"
, "798176 509187"
, "667688 515963"
, "636120 517833"
, "137410 584913"
, "217615 563034"
, "556887 523038"
, "667229 515991"
, "672276 515708"
, "325361 545187"
, "172115 573985"
, "13846 725685"
]
| null | https://raw.githubusercontent.com/ryanpbrewster/haskell/6edd0afe234008a48b4871032dedfd143ca6e412/project-euler/tests/TestData/P099.hs | haskell | module TestData.P099 (txt) where
txt =
unlines
[ "519432 525806"
, "632382 518061"
, "78864 613712"
, "466580 530130"
, "780495 510032"
, "525895 525320"
, "15991 714883"
, "960290 502358"
, "760018 511029"
, "166800 575487"
, "210884 564478"
, "555151 523163"
, "681146 515199"
, "563395 522587"
, "738250 512126"
, "923525 503780"
, "595148 520429"
, "177108 572629"
, "750923 511482"
, "440902 532446"
, "881418 505504"
, "422489 534197"
, "979858 501616"
, "685893 514935"
, "747477 511661"
, "167214 575367"
, "234140 559696"
, "940238 503122"
, "728969 512609"
, "232083 560102"
, "900971 504694"
, "688801 514772"
, "189664 569402"
, "891022 505104"
, "445689 531996"
, "119570 591871"
, "821453 508118"
, "371084 539600"
, "911745 504251"
, "623655 518600"
, "144361 582486"
, "352442 541775"
, "420726 534367"
, "295298 549387"
, "6530 787777"
, "468397 529976"
, "672336 515696"
, "431861 533289"
, "84228 610150"
, "805376 508857"
, "444409 532117"
, "33833 663511"
, "381850 538396"
, "402931 536157"
, "92901 604930"
, "304825 548004"
, "731917 512452"
, "753734 511344"
, "51894 637373"
, "151578 580103"
, "295075 549421"
, "303590 548183"
, "333594 544123"
, "683952 515042"
, "60090 628880"
, "951420 502692"
, "28335 674991"
, "714940 513349"
, "343858 542826"
, "549279 523586"
, "804571 508887"
, "260653 554881"
, "291399 549966"
, "402342 536213"
, "408889 535550"
, "40328 652524"
, "375856 539061"
, "768907 510590"
, "165993 575715"
, "976327 501755"
, "898500 504795"
, "360404 540830"
, "478714 529095"
, "694144 514472"
, "488726 528258"
, "841380 507226"
, "328012 544839"
, "22389 690868"
, "604053 519852"
, "329514 544641"
, "772965 510390"
, "492798 527927"
, "30125 670983"
, "895603 504906"
, "450785 531539"
, "840237 507276"
, "380711 538522"
, "63577 625673"
, "76801 615157"
, "502694 527123"
, "597706 520257"
, "310484 547206"
, "944468 502959"
, "121283 591152"
, "451131 531507"
, "566499 522367"
, "425373 533918"
, "40240 652665"
, "39130 654392"
, "714926 513355"
, "469219 529903"
, "806929 508783"
, "287970 550487"
, "92189 605332"
, "103841 599094"
, "671839 515725"
, "452048 531421"
, "987837 501323"
, "935192 503321"
, "88585 607450"
, "613883 519216"
, "144551 582413"
, "647359 517155"
, "213902 563816"
, "184120 570789"
, "258126 555322"
, "502546 527130"
, "407655 535678"
, "401528 536306"
, "477490 529193"
, "841085 507237"
, "732831 512408"
, "833000 507595"
, "904694 504542"
, "581435 521348"
, "455545 531110"
, "873558 505829"
, "94916 603796"
, "720176 513068"
, "545034 523891"
, "246348 557409"
, "556452 523079"
, "832015 507634"
, "173663 573564"
, "502634 527125"
, "250732 556611"
, "569786 522139"
, "216919 563178"
, "521815 525623"
, "92304 605270"
, "164446 576167"
, "753413 511364"
, "11410 740712"
, "448845 531712"
, "925072 503725"
, "564888 522477"
, "7062 780812"
, "641155 517535"
, "738878 512100"
, "636204 517828"
, "372540 539436"
, "443162 532237"
, "571192 522042"
, "655350 516680"
, "299741 548735"
, "581914 521307"
, "965471 502156"
, "513441 526277"
, "808682 508700"
, "237589 559034"
, "543300 524025"
, "804712 508889"
, "247511 557192"
, "543486 524008"
, "504383 526992"
, "326529 545039"
, "792493 509458"
, "86033 609017"
, "126554 589005"
, "579379 521481"
, "948026 502823"
, "404777 535969"
, "265767 554022"
, "266876 553840"
, "46631 643714"
, "492397 527958"
, "856106 506581"
, "795757 509305"
, "748946 511584"
, "294694 549480"
, "409781 535463"
, "775887 510253"
, "543747 523991"
, "210592 564536"
, "517119 525990"
, "520253 525751"
, "247926 557124"
, "592141 520626"
, "346580 542492"
, "544969 523902"
, "506501 526817"
, "244520 557738"
, "144745 582349"
, "69274 620858"
, "292620 549784"
, "926027 503687"
, "736320 512225"
, "515528 526113"
, "407549 535688"
, "848089 506927"
, "24141 685711"
, "9224 757964"
, "980684 501586"
, "175259 573121"
, "489160 528216"
, "878970 505604"
, "969546 502002"
, "525207 525365"
, "690461 514675"
, "156510 578551"
, "659778 516426"
, "468739 529945"
, "765252 510770"
, "76703 615230"
, "165151 575959"
, "29779 671736"
, "928865 503569"
, "577538 521605"
, "927555 503618"
, "185377 570477"
, "974756 501809"
, "800130 509093"
, "217016 563153"
, "365709 540216"
, "774508 510320"
, "588716 520851"
, "631673 518104"
, "954076 502590"
, "777828 510161"
, "990659 501222"
, "597799 520254"
, "786905 509727"
, "512547 526348"
, "756449 511212"
, "869787 505988"
, "653747 516779"
, "84623 609900"
, "839698 507295"
, "30159 670909"
, "797275 509234"
, "678136 515373"
, "897144 504851"
, "989554 501263"
, "413292 535106"
, "55297 633667"
, "788650 509637"
, "486748 528417"
, "150724 580377"
, "56434 632490"
, "77207 614869"
, "588631 520859"
, "611619 519367"
, "100006 601055"
, "528924 525093"
, "190225 569257"
, "851155 506789"
, "682593 515114"
, "613043 519275"
, "514673 526183"
, "877634 505655"
, "878905 505602"
, "1926 914951"
, "613245 519259"
, "152481 579816"
, "841774 507203"
, "71060 619442"
, "865335 506175"
, "90244 606469"
, "302156 548388"
, "399059 536557"
, "478465 529113"
, "558601 522925"
, "69132 620966"
, "267663 553700"
, "988276 501310"
, "378354 538787"
, "529909 525014"
, "161733 576968"
, "758541 511109"
, "823425 508024"
, "149821 580667"
, "269258 553438"
, "481152 528891"
, "120871 591322"
, "972322 501901"
, "981350 501567"
, "676129 515483"
, "950860 502717"
, "119000 592114"
, "392252 537272"
, "191618 568919"
, "946699 502874"
, "289555 550247"
, "799322 509139"
, "703886 513942"
, "194812 568143"
, "261823 554685"
, "203052 566221"
, "217330 563093"
, "734748 512313"
, "391759 537328"
, "807052 508777"
, "564467 522510"
, "59186 629748"
, "113447 594545"
, "518063 525916"
, "905944 504492"
, "613922 519213"
, "439093 532607"
, "445946 531981"
, "230530 560399"
, "297887 549007"
, "459029 530797"
, "403692 536075"
, "855118 506616"
, "963127 502245"
, "841711 507208"
, "407411 535699"
, "924729 503735"
, "914823 504132"
, "333725 544101"
, "176345 572832"
, "912507 504225"
, "411273 535308"
, "259774 555036"
, "632853 518038"
, "119723 591801"
, "163902 576321"
, "22691 689944"
, "402427 536212"
, "175769 572988"
, "837260 507402"
, "603432 519893"
, "313679 546767"
, "538165 524394"
, "549026 523608"
, "61083 627945"
, "898345 504798"
, "992556 501153"
, "369999 539727"
, "32847 665404"
, "891292 505088"
, "152715 579732"
, "824104 507997"
, "234057 559711"
, "730507 512532"
, "960529 502340"
, "388395 537687"
, "958170 502437"
, "57105 631806"
, "186025 570311"
, "993043 501133"
, "576770 521664"
, "215319 563513"
, "927342 503628"
, "521353 525666"
, "39563 653705"
, "752516 511408"
, "110755 595770"
, "309749 547305"
, "374379 539224"
, "919184 503952"
, "990652 501226"
, "647780 517135"
, "187177 570017"
, "168938 574877"
, "649558 517023"
, "278126 552016"
, "162039 576868"
, "658512 516499"
, "498115 527486"
, "896583 504868"
, "561170 522740"
, "747772 511647"
, "775093 510294"
, "652081 516882"
, "724905 512824"
, "499707 527365"
, "47388 642755"
, "646668 517204"
, "571700 522007"
, "180430 571747"
, "710015 513617"
, "435522 532941"
, "98137 602041"
, "759176 511070"
, "486124 528467"
, "526942 525236"
, "878921 505604"
, "408313 535602"
, "926980 503640"
, "882353 505459"
, "566887 522345"
, "3326 853312"
, "911981 504248"
, "416309 534800"
, "392991 537199"
, "622829 518651"
, "148647 581055"
, "496483 527624"
, "666314 516044"
, "48562 641293"
, "672618 515684"
, "443676 532187"
, "274065 552661"
, "265386 554079"
, "347668 542358"
, "31816 667448"
, "181575 571446"
, "961289 502320"
, "365689 540214"
, "987950 501317"
, "932299 503440"
, "27388 677243"
, "746701 511701"
, "492258 527969"
, "147823 581323"
, "57918 630985"
, "838849 507333"
, "678038 515375"
, "27852 676130"
, "850241 506828"
, "818403 508253"
, "131717 587014"
, "850216 506834"
, "904848 504529"
, "189758 569380"
, "392845 537217"
, "470876 529761"
, "925353 503711"
, "285431 550877"
, "454098 531234"
, "823910 508003"
, "318493 546112"
, "766067 510730"
, "261277 554775"
, "421530 534289"
, "694130 514478"
, "120439 591498"
, "213308 563949"
, "854063 506662"
, "365255 540263"
, "165437 575872"
, "662240 516281"
, "289970 550181"
, "847977 506933"
, "546083 523816"
, "413252 535113"
, "975829 501767"
, "361540 540701"
, "235522 559435"
, "224643 561577"
, "736350 512229"
, "328303 544808"
, "35022 661330"
, "307838 547578"
, "474366 529458"
, "873755 505819"
, "73978 617220"
, "827387 507845"
, "670830 515791"
, "326511 545034"
, "309909 547285"
, "400970 536363"
, "884827 505352"
, "718307 513175"
, "28462 674699"
, "599384 520150"
, "253565 556111"
, "284009 551093"
, "343403 542876"
, "446557 531921"
, "992372 501160"
, "961601 502308"
, "696629 514342"
, "919537 503945"
, "894709 504944"
, "892201 505051"
, "358160 541097"
, "448503 531745"
, "832156 507636"
, "920045 503924"
, "926137 503675"
, "416754 534757"
, "254422 555966"
, "92498 605151"
, "826833 507873"
, "660716 516371"
, "689335 514746"
, "160045 577467"
, "814642 508425"
, "969939 501993"
, "242856 558047"
, "76302 615517"
, "472083 529653"
, "587101 520964"
, "99066 601543"
, "498005 527503"
, "709800 513624"
, "708000 513716"
, "20171 698134"
, "285020 550936"
, "266564 553891"
, "981563 501557"
, "846502 506991"
, "334 1190800"
, "209268 564829"
, "9844 752610"
, "996519 501007"
, "410059 535426"
, "432931 533188"
, "848012 506929"
, "966803 502110"
, "983434 501486"
, "160700 577267"
, "504374 526989"
, "832061 507640"
, "392825 537214"
, "443842 532165"
, "440352 532492"
, "745125 511776"
, "13718 726392"
, "661753 516312"
, "70500 619875"
, "436952 532814"
, "424724 533973"
, "21954 692224"
, "262490 554567"
, "716622 513264"
, "907584 504425"
, "60086 628882"
, "837123 507412"
, "971345 501940"
, "947162 502855"
, "139920 584021"
, "68330 621624"
, "666452 516038"
, "731446 512481"
, "953350 502619"
, "183157 571042"
, "845400 507045"
, "651548 516910"
, "20399 697344"
, "861779 506331"
, "629771 518229"
, "801706 509026"
, "189207 569512"
, "737501 512168"
, "719272 513115"
, "479285 529045"
, "136046 585401"
, "896746 504860"
, "891735 505067"
, "684771 514999"
, "865309 506184"
, "379066 538702"
, "503117 527090"
, "621780 518717"
, "209518 564775"
, "677135 515423"
, "987500 501340"
, "197049 567613"
, "329315 544673"
, "236756 559196"
, "357092 541226"
, "520440 525733"
, "213471 563911"
, "956852 502490"
, "702223 514032"
, "404943 535955"
, "178880 572152"
, "689477 514734"
, "691351 514630"
, "866669 506128"
, "370561 539656"
, "739805 512051"
, "71060 619441"
, "624861 518534"
, "261660 554714"
, "366137 540160"
, "166054 575698"
, "601878 519990"
, "153445 579501"
, "279899 551729"
, "379166 538691"
, "423209 534125"
, "675310 515526"
, "145641 582050"
, "691353 514627"
, "917468 504026"
, "284778 550976"
, "81040 612235"
, "161699 576978"
, "616394 519057"
, "767490 510661"
, "156896 578431"
, "427408 533714"
, "254849 555884"
, "737217 512182"
, "897133 504851"
, "203815 566051"
, "270822 553189"
, "135854 585475"
, "778805 510111"
, "784373 509847"
, "305426 547921"
, "733418 512375"
, "732087 512448"
, "540668 524215"
, "702898 513996"
, "628057 518328"
, "640280 517587"
, "422405 534204"
, "10604 746569"
, "746038 511733"
, "839808 507293"
, "457417 530938"
, "479030 529064"
, "341758 543090"
, "620223 518824"
, "251661 556451"
, "561790 522696"
, "497733 527521"
, "724201 512863"
, "489217 528217"
, "415623 534867"
, "624610 518548"
, "847541 506953"
, "432295 533249"
, "400391 536421"
, "961158 502319"
, "139173 584284"
, "421225 534315"
, "579083 521501"
, "74274 617000"
, "701142 514087"
, "374465 539219"
, "217814 562985"
, "358972 540995"
, "88629 607424"
, "288597 550389"
, "285819 550812"
, "538400 524385"
, "809930 508645"
, "738326 512126"
, "955461 502535"
, "163829 576343"
, "826475 507891"
, "376488 538987"
, "102234 599905"
, "114650 594002"
, "52815 636341"
, "434037 533082"
, "804744 508880"
, "98385 601905"
, "856620 506559"
, "220057 562517"
, "844734 507078"
, "150677 580387"
, "558697 522917"
, "621751 518719"
, "207067 565321"
, "135297 585677"
, "932968 503404"
, "604456 519822"
, "579728 521462"
, "244138 557813"
, "706487 513800"
, "711627 513523"
, "853833 506674"
, "497220 527562"
, "59428 629511"
, "564845 522486"
, "623621 518603"
, "242689 558077"
, "125091 589591"
, "363819 540432"
, "686453 514901"
, "656813 516594"
, "489901 528155"
, "386380 537905"
, "542819 524052"
, "243987 557841"
, "693412 514514"
, "488484 528271"
, "896331 504881"
, "336730 543721"
, "728298 512647"
, "604215 519840"
, "153729 579413"
, "595687 520398"
, "540360 524240"
, "245779 557511"
, "924873 503730"
, "509628 526577"
, "528523 525122"
, "3509 847707"
, "522756 525555"
, "895447 504922"
, "44840 646067"
, "45860 644715"
, "463487 530404"
, "398164 536654"
, "894483 504959"
, "619415 518874"
, "966306 502129"
, "990922 501212"
, "835756 507474"
, "548881 523618"
, "453578 531282"
, "474993 529410"
, "80085 612879"
, "737091 512193"
, "50789 638638"
, "979768 501620"
, "792018 509483"
, "665001 516122"
, "86552 608694"
, "462772 530469"
, "589233 520821"
, "891694 505072"
, "592605 520594"
, "209645 564741"
, "42531 649269"
, "554376 523226"
, "803814 508929"
, "334157 544042"
, "175836 572970"
, "868379 506051"
, "658166 516520"
, "278203 551995"
, "966198 502126"
, "627162 518387"
, "296774 549165"
, "311803 547027"
, "843797 507118"
, "702304 514032"
, "563875 522553"
, "33103 664910"
, "191932 568841"
, "543514 524006"
, "506835 526794"
, "868368 506052"
, "847025 506971"
, "678623 515342"
, "876139 505726"
, "571997 521984"
, "598632 520198"
, "213590 563892"
, "625404 518497"
, "726508 512738"
, "689426 514738"
, "332495 544264"
, "411366 535302"
, "242546 558110"
, "315209 546555"
, "797544 509219"
, "93889 604371"
, "858879 506454"
, "124906 589666"
, "449072 531693"
, "235960 559345"
, "642403 517454"
, "720567 513047"
, "705534 513858"
, "603692 519870"
, "488137 528302"
, "157370 578285"
, "63515 625730"
, "666326 516041"
, "619226 518883"
, "443613 532186"
, "597717 520257"
, "96225 603069"
, "86940 608450"
, "40725 651929"
, "460976 530625"
, "268875 553508"
, "270671 553214"
, "363254 540500"
, "384248 538137"
, "762889 510892"
, "377941 538833"
, "278878 551890"
, "176615 572755"
, "860008 506412"
, "944392 502967"
, "608395 519571"
, "225283 561450"
, "45095 645728"
, "333798 544090"
, "625733 518476"
, "995584 501037"
, "506135 526853"
, "238050 558952"
, "557943 522972"
, "530978 524938"
, "634244 517949"
, "177168 572616"
, "85200 609541"
, "953043 502630"
, "523661 525484"
, "999295 500902"
, "840803 507246"
, "961490 502312"
, "471747 529685"
, "380705 538523"
, "911180 504275"
, "334149 544046"
, "478992 529065"
, "325789 545133"
, "335884 543826"
, "426976 533760"
, "749007 511582"
, "667067 516000"
, "607586 519623"
, "674054 515599"
, "188534 569675"
, "565185 522464"
, "172090 573988"
, "87592 608052"
, "907432 504424"
, "8912 760841"
, "928318 503590"
, "757917 511138"
, "718693 513153"
, "315141 546566"
, "728326 512645"
, "353492 541647"
, "638429 517695"
, "628892 518280"
, "877286 505672"
, "620895 518778"
, "385878 537959"
, "423311 534113"
, "633501 517997"
, "884833 505360"
, "883402 505416"
, "999665 500894"
, "708395 513697"
, "548142 523667"
, "756491 511205"
, "987352 501340"
, "766520 510705"
, "591775 520647"
, "833758 507563"
, "843890 507108"
, "925551 503698"
, "74816 616598"
, "646942 517187"
, "354923 541481"
, "256291 555638"
, "634470 517942"
, "930904 503494"
, "134221 586071"
, "282663 551304"
, "986070 501394"
, "123636 590176"
, "123678 590164"
, "481717 528841"
, "423076 534137"
, "866246 506145"
, "93313 604697"
, "783632 509880"
, "317066 546304"
, "502977 527103"
, "141272 583545"
, "71708 618938"
, "617748 518975"
, "581190 521362"
, "193824 568382"
, "682368 515131"
, "352956 541712"
, "351375 541905"
, "505362 526909"
, "905165 504518"
, "128645 588188"
, "267143 553787"
, "158409 577965"
, "482776 528754"
, "628896 518282"
, "485233 528547"
, "563606 522574"
, "111001 595655"
, "115920 593445"
, "365510 540237"
, "959724 502374"
, "938763 503184"
, "930044 503520"
, "970959 501956"
, "913658 504176"
, "68117 621790"
, "989729 501253"
, "567697 522288"
, "820427 508163"
, "54236 634794"
, "291557 549938"
, "124961 589646"
, "403177 536130"
, "405421 535899"
, "410233 535417"
, "815111 508403"
, "213176 563974"
, "83099 610879"
, "998588 500934"
, "513640 526263"
, "129817 587733"
, "1820 921851"
, "287584 550539"
, "299160 548820"
, "860621 506386"
, "529258 525059"
, "586297 521017"
, "953406 502616"
, "441234 532410"
, "986217 501386"
, "781938 509957"
, "461247 530595"
, "735424 512277"
, "146623 581722"
, "839838 507288"
, "510667 526494"
, "935085 503327"
, "737523 512167"
, "303455 548204"
, "992779 501145"
, "60240 628739"
, "939095 503174"
, "794368 509370"
, "501825 527189"
, "459028 530798"
, "884641 505363"
, "512287 526364"
, "835165 507499"
, "307723 547590"
, "160587 577304"
, "735043 512300"
, "493289 527887"
, "110717 595785"
, "306480 547772"
, "318593 546089"
, "179810 571911"
, "200531 566799"
, "314999 546580"
, "197020 567622"
, "301465 548487"
, "237808 559000"
, "131944 586923"
, "882527 505449"
, "468117 530003"
, "711319 513541"
, "156240 578628"
, "965452 502162"
, "992756 501148"
, "437959 532715"
, "739938 512046"
, "614249 519196"
, "391496 537356"
, "62746 626418"
, "688215 514806"
, "75501 616091"
, "883573 505412"
, "558824 522910"
, "759371 511061"
, "173913 573489"
, "891351 505089"
, "727464 512693"
, "164833 576051"
, "812317 508529"
, "540320 524243"
, "698061 514257"
, "69149 620952"
, "471673 529694"
, "159092 577753"
, "428134 533653"
, "89997 606608"
, "711061 513557"
, "779403 510081"
, "203327 566155"
, "798176 509187"
, "667688 515963"
, "636120 517833"
, "137410 584913"
, "217615 563034"
, "556887 523038"
, "667229 515991"
, "672276 515708"
, "325361 545187"
, "172115 573985"
, "13846 725685"
]
| |
f20f7bc3b9327c99f9795703ef4694cf74141fd952904b9a714ef33a0f956afb | OCamlPro/ocplib-json-typed | json_repr_browser.ml | This file is part of Learn - OCaml .
*
* Copyright ( C ) 2016 OCamlPro .
*
* Learn - OCaml is free software : you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation , either version 3 of the
* License , or ( at your option ) any later version .
*
* Learn - OCaml is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Affero General Public License for more details .
*
* You should have received a copy of the GNU Affero General Public License
* along with this program . If not , see < / > .
*
* Copyright (C) 2016 OCamlPro.
*
* Learn-OCaml is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Learn-OCaml is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see </>. *)
module Repr = struct
(* Not for the faint of heart. *)
type value = unit Js.t
let repr = function
| `String s -> Js.Unsafe.coerce (Js.string s)
| `Float f -> Js.Unsafe.coerce (Obj.magic f)
| `Bool true -> Js.Unsafe.coerce Js._true
| `Bool false -> Js.Unsafe.coerce Js._false
Oh , !
| `O fields ->
let obj = Js.Unsafe.new_obj (Js.Unsafe.pure_js_expr "Object") [||] in
List.iter
(fun (n, v) -> Js.Unsafe.set obj (Js.string n) v)
fields ;
obj
| `A cells ->
Js.Unsafe.coerce (Js.array (Array.of_list cells))
let view v =
match Js.to_string (Js.typeof v) with
| "string" -> `String (Js.to_string (Js.Unsafe.coerce v))
| "number" -> `Float (Obj.magic v)
| "boolean" -> `Bool (Js.to_bool (Obj.magic v))
| "undefined" -> `Null (* Oh yeah! *)
| "object" ->
if v == Js.Unsafe.pure_js_expr "null" then
`Null
else if Js.instanceof v (Js.Unsafe.pure_js_expr "Array") then
let rec loop acc n =
if n < 0 then
`A acc
else
loop (Js.Unsafe.get v n :: acc) (n - 1)
in
loop [] (Js.Unsafe.get v (Js.string "length") - 1)
else
let fields : Js.js_string Js.t list =
Array.to_list @@ Js.to_array
(Js.Unsafe.fun_call
(Js.Unsafe.js_expr
"(function(o){\
\ var p=[];\
\ for(var n in o){if(o.hasOwnProperty(n)){p.push(n);}}\
\ return p;\
})")
[| Js.Unsafe.inject v |]) in
`O (List.map
(fun f -> Js.to_string f, Js.Unsafe.get v f)
fields)
| _ -> invalid_arg "Json_repr_browser.Repr.view"
let repr_uid = Json_repr.repr_uid ()
end
type value = Repr.value
let js_stringify ?indent obj =
Js.Unsafe.meth_call
(Js.Unsafe.variable "JSON")
"stringify"
(match indent with
| None ->
[| Js.Unsafe.inject obj |]
| Some indent ->
[| Js.Unsafe.inject obj ;
Js.Unsafe.inject Js.null ;
Js.Unsafe.inject indent |])
let parse_js_string jsstr =
Js.Unsafe.meth_call
(Js.Unsafe.variable "JSON")
"parse"
[| Js.Unsafe.inject jsstr |]
let stringify ?indent obj =
Js.to_string (js_stringify ?indent obj)
let parse str =
parse_js_string (Js.string str)
module Json_encoding = Json_encoding.Make (Repr)
module Json_query = Json_query.Make (Repr)
| null | https://raw.githubusercontent.com/OCamlPro/ocplib-json-typed/0d9e9cde74c7c50aa6d053990b46f5930c80de54/src/json_repr_browser.ml | ocaml | Not for the faint of heart.
Oh yeah! | This file is part of Learn - OCaml .
*
* Copyright ( C ) 2016 OCamlPro .
*
* Learn - OCaml is free software : you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation , either version 3 of the
* License , or ( at your option ) any later version .
*
* Learn - OCaml is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Affero General Public License for more details .
*
* You should have received a copy of the GNU Affero General Public License
* along with this program . If not , see < / > .
*
* Copyright (C) 2016 OCamlPro.
*
* Learn-OCaml is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Learn-OCaml is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see </>. *)
module Repr = struct
type value = unit Js.t
let repr = function
| `String s -> Js.Unsafe.coerce (Js.string s)
| `Float f -> Js.Unsafe.coerce (Obj.magic f)
| `Bool true -> Js.Unsafe.coerce Js._true
| `Bool false -> Js.Unsafe.coerce Js._false
Oh , !
| `O fields ->
let obj = Js.Unsafe.new_obj (Js.Unsafe.pure_js_expr "Object") [||] in
List.iter
(fun (n, v) -> Js.Unsafe.set obj (Js.string n) v)
fields ;
obj
| `A cells ->
Js.Unsafe.coerce (Js.array (Array.of_list cells))
let view v =
match Js.to_string (Js.typeof v) with
| "string" -> `String (Js.to_string (Js.Unsafe.coerce v))
| "number" -> `Float (Obj.magic v)
| "boolean" -> `Bool (Js.to_bool (Obj.magic v))
| "object" ->
if v == Js.Unsafe.pure_js_expr "null" then
`Null
else if Js.instanceof v (Js.Unsafe.pure_js_expr "Array") then
let rec loop acc n =
if n < 0 then
`A acc
else
loop (Js.Unsafe.get v n :: acc) (n - 1)
in
loop [] (Js.Unsafe.get v (Js.string "length") - 1)
else
let fields : Js.js_string Js.t list =
Array.to_list @@ Js.to_array
(Js.Unsafe.fun_call
(Js.Unsafe.js_expr
"(function(o){\
\ var p=[];\
\ for(var n in o){if(o.hasOwnProperty(n)){p.push(n);}}\
\ return p;\
})")
[| Js.Unsafe.inject v |]) in
`O (List.map
(fun f -> Js.to_string f, Js.Unsafe.get v f)
fields)
| _ -> invalid_arg "Json_repr_browser.Repr.view"
let repr_uid = Json_repr.repr_uid ()
end
type value = Repr.value
let js_stringify ?indent obj =
Js.Unsafe.meth_call
(Js.Unsafe.variable "JSON")
"stringify"
(match indent with
| None ->
[| Js.Unsafe.inject obj |]
| Some indent ->
[| Js.Unsafe.inject obj ;
Js.Unsafe.inject Js.null ;
Js.Unsafe.inject indent |])
let parse_js_string jsstr =
Js.Unsafe.meth_call
(Js.Unsafe.variable "JSON")
"parse"
[| Js.Unsafe.inject jsstr |]
let stringify ?indent obj =
Js.to_string (js_stringify ?indent obj)
let parse str =
parse_js_string (Js.string str)
module Json_encoding = Json_encoding.Make (Repr)
module Json_query = Json_query.Make (Repr)
|
01a69bffc70606fd666f1ee2b4ae6be47f418f96e5fa612df85cf7ac78c84081 | onedata/op-worker | atm_task_execution_status.erl | %%%-------------------------------------------------------------------
@author
( C ) 2021 - 2022 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
%%% @end
%%%-------------------------------------------------------------------
%%% @doc
%%% This module contains functions that handle atm task execution status
%%% transitions according (with some exceptions described below) to following
%%% state machine:
%%% |
%%% v
%%% ------------------------------ +-----------+ <---- no item ever scheduled
%%% / | PENDING | \
%%% | ------------------- +-----------+ \
%%% | / | \ +----------+
%%% | task execution stopped | resumed with ----- | RESUMING | --------
%%% | with no item ever first item / +----------+ \
%%% | scheduled to process scheduled to process / ^ |
%%% | | / / | |
%%% | | | ----------------------------- else | |
%%% | | | / | |
%%% | | | | ____ overriding | |
%%% | | v v / \ ^stopping | |
%%% | | +----------+ +------------+ / reason | |
%%% | | | ACTIVE | ------ ^stopping -------> | STOPPING | <-- | |
%%% | | +----------+ +------------+ | |
%%% | | | / | |
%%% | | task execution stopped --------- / |
%%% | | with all items / resuming execution / |
%%% | | processed | -----------------o----------- |
%%% | | / \ | / | |
%%% | | successfully else | / -------------|------- 4* ---- |
%%% | | | | | / / | \ |
%%% | v v v | / / | v |
%%% | +-----------+ +----------+ +--------+ | +-------------+ +--------+ +-----------+ |
%%% | | SKIPPED | | FINISHED | | FAILED | | | INTERRUPTED | <- 2* - | PAUSED | - 4* -> | CANCELLED | |
%%% | +-----------+ +----------+ +--------+ | +-------------+ +--------+ +-----------+ |
%%% | ^ | ^ ^ ^ |
%%% | | | | | | |
%%% | 1* | 2* 3* 4* |
%%% | \ v | | / |
%%% | [ task execution stopped due to ^stopping reason ] |
%%% | ^ ^ |
%%% \ / \ /
%%% --------------------------------------------- --------------
%%%
Task transition to STOPPING status when execution is halted and not all items were processed .
%%% It is necessary as results for already scheduled ones must be awaited even if no more items are scheduled.
%%% In case when all items were already processed, such intermediate transition is omitted (transition
from ACTIVE to stopped status can be done during one update operation ) - although
%%% logically such transition occurs.
%%% Possible reasons for ^stopping task execution when not all items were processed are as follows:
1 * - failure severe enough to cause stopping of entire automation workflow execution
%%% (e.g. error when processing uncorrelated results) or interruption of active task
%%% if it has any uncorrelated results (some of them may have been lost).
2 * - abrupt interruption when some other component ( e.g task or external service like OpenFaaS )
%%% has failed and entire automation workflow execution is being stopped.
3 * - user pausing entire automation workflow execution .
4 * - user cancelling entire automation workflow execution .
%%% @end
%%%-------------------------------------------------------------------
-module(atm_task_execution_status).
-author("Bartosz Walkowicz").
-include("modules/automation/atm_execution.hrl").
%% API
-export([is_transition_allowed/2, is_running/1]).
-export([
handle_items_in_processing/2,
handle_item_processed/1,
handle_items_withdrawn/2,
handle_items_failed/2,
handle_stopping/3,
handle_stopped/1,
handle_resuming/2,
handle_resumed/1
]).
%%%===================================================================
%%% API functions
%%%===================================================================
-spec is_transition_allowed(atm_task_execution:status(), atm_task_execution:status()) ->
boolean().
is_transition_allowed(?PENDING_STATUS, ?SKIPPED_STATUS) -> true;
is_transition_allowed(?PENDING_STATUS, ?INTERRUPTED_STATUS) -> true;
is_transition_allowed(?PENDING_STATUS, ?PAUSED_STATUS) -> true;
is_transition_allowed(?PENDING_STATUS, ?CANCELLED_STATUS) -> true;
is_transition_allowed(?PENDING_STATUS, ?ACTIVE_STATUS) -> true;
is_transition_allowed(?ACTIVE_STATUS, ?FINISHED_STATUS) -> true;
is_transition_allowed(?ACTIVE_STATUS, ?FAILED_STATUS) -> true;
is_transition_allowed(?ACTIVE_STATUS, ?STOPPING_STATUS) -> true;
is_transition_allowed(?STOPPING_STATUS, ?FAILED_STATUS) -> true;
is_transition_allowed(?STOPPING_STATUS, ?INTERRUPTED_STATUS) -> true;
is_transition_allowed(?STOPPING_STATUS, ?PAUSED_STATUS) -> true;
is_transition_allowed(?STOPPING_STATUS, ?CANCELLED_STATUS) -> true;
is_transition_allowed(?PAUSED_STATUS, ?INTERRUPTED_STATUS) -> true;
is_transition_allowed(?PAUSED_STATUS, ?CANCELLED_STATUS) -> true;
% Transition possible in case of race between resuming interrupted task and pausing it
( normally task should first transition to RESUMING status and only then to PAUSED )
is_transition_allowed(?INTERRUPTED_STATUS, ?PAUSED_STATUS) -> true;
is_transition_allowed(?INTERRUPTED_STATUS, ?CANCELLED_STATUS) -> true;
is_transition_allowed(?INTERRUPTED_STATUS, ?RESUMING_STATUS) -> true;
is_transition_allowed(?PAUSED_STATUS, ?RESUMING_STATUS) -> true;
is_transition_allowed(?RESUMING_STATUS, ?INTERRUPTED_STATUS) -> true;
is_transition_allowed(?RESUMING_STATUS, ?PAUSED_STATUS) -> true;
is_transition_allowed(?RESUMING_STATUS, ?CANCELLED_STATUS) -> true;
is_transition_allowed(?RESUMING_STATUS, ?PENDING_STATUS) -> true;
is_transition_allowed(?RESUMING_STATUS, ?ACTIVE_STATUS) -> true;
is_transition_allowed(_, _) -> false.
-spec is_running(atm_task_execution:status()) -> boolean().
is_running(?RESUMING_STATUS) -> true;
is_running(?PENDING_STATUS) -> true;
is_running(?ACTIVE_STATUS) -> true;
is_running(?STOPPING_STATUS) -> true;
is_running(_) -> false.
-spec handle_items_in_processing(atm_task_execution:id(), pos_integer()) ->
{ok, atm_task_execution:doc()} | {error, task_already_stopping} | {error, task_already_stopped}.
handle_items_in_processing(AtmTaskExecutionId, ItemCount) ->
apply_diff(AtmTaskExecutionId, fun
(AtmTaskExecution = #atm_task_execution{
status = ?PENDING_STATUS,
items_in_processing = 0
}) ->
{ok, AtmTaskExecution#atm_task_execution{
status = ?ACTIVE_STATUS,
items_in_processing = ItemCount
}};
(AtmTaskExecution = #atm_task_execution{
status = ?ACTIVE_STATUS,
items_in_processing = CurrentItemsInProcessingNum
}) ->
{ok, AtmTaskExecution#atm_task_execution{
items_in_processing = CurrentItemsInProcessingNum + ItemCount
}};
(#atm_task_execution{status = ?STOPPING_STATUS}) ->
{error, task_already_stopping};
(#atm_task_execution{status = Status}) when
Status =:= ?SKIPPED_STATUS;
Status =:= ?INTERRUPTED_STATUS;
Status =:= ?PAUSED_STATUS;
Status =:= ?FINISHED_STATUS;
Status =:= ?FAILED_STATUS;
Status =:= ?CANCELLED_STATUS
->
{error, task_already_stopped}
end).
-spec handle_item_processed(atm_task_execution:id()) -> ok.
handle_item_processed(AtmTaskExecutionId) ->
{ok, _} = apply_diff(AtmTaskExecutionId, fun(#atm_task_execution{
items_in_processing = ItemsInProcessing,
items_processed = ItemsProcessed
} = AtmTaskExecution) ->
{ok, AtmTaskExecution#atm_task_execution{
items_in_processing = ItemsInProcessing - 1,
items_processed = ItemsProcessed + 1
}}
end),
ok.
-spec handle_items_withdrawn(atm_task_execution:id(), pos_integer()) ->
{ok, atm_task_execution:doc()} | {error, task_not_stopping}.
handle_items_withdrawn(AtmTaskExecutionId, ItemCount) ->
apply_diff(AtmTaskExecutionId, fun
(AtmTaskExecution = #atm_task_execution{
status = ?STOPPING_STATUS,
items_in_processing = ItemsInProcessing
}) ->
{ok, AtmTaskExecution#atm_task_execution{
items_in_processing = ItemsInProcessing - ItemCount
}};
(_) ->
{error, task_not_stopping}
end).
-spec handle_items_failed(atm_task_execution:id(), pos_integer()) -> ok.
handle_items_failed(AtmTaskExecutionId, ItemCount) ->
{ok, _} = apply_diff(AtmTaskExecutionId, fun(#atm_task_execution{
items_in_processing = ItemsInProcessing,
items_processed = ItemsProcessed,
items_failed = ItemsFailed
} = AtmTaskExecution) ->
{ok, AtmTaskExecution#atm_task_execution{
items_in_processing = ItemsInProcessing - ItemCount,
items_processed = ItemsProcessed + ItemCount,
items_failed = ItemsFailed + ItemCount
}}
end),
ok.
-spec handle_stopping(
atm_task_execution:id(),
atm_task_execution:stopping_reason(),
atm_workflow_execution:incarnation()
) ->
{ok, atm_task_execution:doc()} | {error, task_already_stopping} | {error, task_already_stopped}.
handle_stopping(AtmTaskExecutionId, Reason, CurrentIncarnation) ->
apply_diff(AtmTaskExecutionId, fun
(AtmTaskExecution = #atm_task_execution{status = Status}) when
Status =:= ?PENDING_STATUS;
Status =:= ?RESUMING_STATUS
->
{ok, AtmTaskExecution#atm_task_execution{
status = infer_stopped_status(Reason),
stopping_incarnation = CurrentIncarnation
}};
(AtmTaskExecution = #atm_task_execution{status = ?ACTIVE_STATUS}) ->
{ok, AtmTaskExecution#atm_task_execution{
status = ?STOPPING_STATUS,
stopping_reason = Reason,
stopping_incarnation = CurrentIncarnation
}};
(AtmTaskExecution = #atm_task_execution{
status = ?STOPPING_STATUS,
stopping_reason = PrevReason
}) ->
case should_overwrite_stopping_reason(PrevReason, Reason) of
true -> {ok, AtmTaskExecution#atm_task_execution{stopping_reason = Reason}};
false -> {error, task_already_stopping}
end;
(AtmTaskExecution = #atm_task_execution{status = ?PAUSED_STATUS}) when
Reason =:= cancel;
Reason =:= interrupt
->
{ok, AtmTaskExecution#atm_task_execution{
status = infer_stopped_status(Reason),
stopping_reason = Reason,
stopping_incarnation = CurrentIncarnation
}};
(AtmTaskExecution = #atm_task_execution{
status = ?INTERRUPTED_STATUS,
stopping_incarnation = PrevStoppingIncarnation
}) when
Reason =:= cancel;
% Possible race condition when resuming and immediately pausing interrupted task (resuming
% traverse hasn't yet transition task to RESUMING status while pausing traverse pauses it)
(Reason =:= pause andalso PrevStoppingIncarnation < CurrentIncarnation)
->
{ok, AtmTaskExecution#atm_task_execution{
status = infer_stopped_status(Reason),
stopping_reason = Reason,
stopping_incarnation = CurrentIncarnation
}};
(#atm_task_execution{status = Status}) when
Status =:= ?SKIPPED_STATUS;
Status =:= ?INTERRUPTED_STATUS;
Status =:= ?PAUSED_STATUS;
Status =:= ?FINISHED_STATUS;
Status =:= ?FAILED_STATUS;
Status =:= ?CANCELLED_STATUS
->
{error, task_already_stopped}
end).
-spec handle_stopped(atm_task_execution:id()) ->
{ok, atm_task_execution:doc()} | {error, task_already_stopped}.
handle_stopped(AtmTaskExecutionId) ->
apply_diff(AtmTaskExecutionId, fun
(AtmTaskExecution = #atm_task_execution{status = ?PENDING_STATUS}) ->
{ok, AtmTaskExecution#atm_task_execution{status = ?SKIPPED_STATUS}};
(AtmTaskExecution = #atm_task_execution{
status = ?ACTIVE_STATUS,
items_in_processing = 0,
items_failed = 0
}) ->
{ok, AtmTaskExecution#atm_task_execution{status = ?FINISHED_STATUS}};
(AtmTaskExecution = #atm_task_execution{
status = ?ACTIVE_STATUS,
items_in_processing = 0
}) ->
% All jobs were executed but some must have failed
{ok, AtmTaskExecution#atm_task_execution{status = ?FAILED_STATUS}};
(AtmTaskExecution = #atm_task_execution{
status = ?STOPPING_STATUS,
stopping_reason = StoppingReason,
items_in_processing = ItemsInProcessing,
items_processed = ItemsProcessed,
items_failed = ItemsFailed,
uncorrelated_result_specs = UncorrelatedResultSpecs
}) ->
% atm workflow execution may have been abruptly interrupted by e.g.
% provider restart which resulted in stale `items_in_processing`
UpdatedProcessedItems = ItemsProcessed + ItemsInProcessing,
UpdatedFailedItems = ItemsFailed + ItemsInProcessing,
{ok, AtmTaskExecution#atm_task_execution{
status = case {StoppingReason, lists_utils:is_empty(UncorrelatedResultSpecs)} of
{interrupt, false} ->
% If task having uncorrelated results is interrupted not all of those
% results may have been received and as such it is treated as failure
% rather then interruption
?FAILED_STATUS;
_ ->
infer_stopped_status(StoppingReason)
end,
items_in_processing = 0,
items_processed = UpdatedProcessedItems,
items_failed = UpdatedFailedItems
}};
(#atm_task_execution{status = Status}) when
Status =:= ?SKIPPED_STATUS;
Status =:= ?INTERRUPTED_STATUS;
Status =:= ?PAUSED_STATUS;
Status =:= ?FINISHED_STATUS;
Status =:= ?FAILED_STATUS;
Status =:= ?CANCELLED_STATUS
->
{error, task_already_stopped}
end).
-spec handle_resuming(atm_task_execution:id(), atm_workflow_execution:incarnation()) ->
{ok, atm_task_execution:doc()} | {error, task_already_stopped}.
handle_resuming(AtmTaskExecutionId, CurrentIncarnation) ->
apply_diff(AtmTaskExecutionId, fun
(AtmTaskExecution = #atm_task_execution{
status = Status,
stopping_incarnation = PrevStoppingIncarnation
}) when
(Status =:= ?INTERRUPTED_STATUS orelse Status =:= ?PAUSED_STATUS),
% Ensure status wasn't updated by parallel pause/interrupt (possible race)
% in current incarnation
PrevStoppingIncarnation < CurrentIncarnation
->
{ok, AtmTaskExecution#atm_task_execution{
status = ?RESUMING_STATUS,
stopping_reason = undefined
}};
(#atm_task_execution{status = Status}) when
Status =:= ?SKIPPED_STATUS;
Status =:= ?INTERRUPTED_STATUS;
Status =:= ?PAUSED_STATUS;
Status =:= ?FINISHED_STATUS;
Status =:= ?FAILED_STATUS;
Status =:= ?CANCELLED_STATUS
->
{error, task_already_stopped}
end).
-spec handle_resumed(atm_task_execution:id()) ->
{ok, atm_task_execution:doc()} | {error, task_already_stopped}.
handle_resumed(AtmTaskExecutionId) ->
apply_diff(AtmTaskExecutionId, fun
(AtmTaskExecution = #atm_task_execution{
status = ?RESUMING_STATUS,
items_in_processing = 0,
items_processed = 0,
items_failed = 0
}) ->
{ok, AtmTaskExecution#atm_task_execution{status = ?PENDING_STATUS}};
(AtmTaskExecution = #atm_task_execution{status = ?RESUMING_STATUS}) ->
{ok, AtmTaskExecution#atm_task_execution{status = ?ACTIVE_STATUS}};
(#atm_task_execution{status = Status}) when
Status =:= ?SKIPPED_STATUS;
Status =:= ?INTERRUPTED_STATUS;
Status =:= ?PAUSED_STATUS;
Status =:= ?FINISHED_STATUS;
Status =:= ?FAILED_STATUS;
Status =:= ?CANCELLED_STATUS
->
{error, task_already_stopped}
end).
%%%===================================================================
Internal functions
%%%===================================================================
@private
-spec infer_stopped_status(atm_task_execution:stopping_reason()) -> atm_task_execution:status().
infer_stopped_status(pause) -> ?PAUSED_STATUS;
infer_stopped_status(interrupt) -> ?INTERRUPTED_STATUS;
infer_stopped_status(failure) -> ?FAILED_STATUS;
infer_stopped_status(cancel) -> ?CANCELLED_STATUS.
@private
-spec should_overwrite_stopping_reason(
atm_task_execution:stopping_reason(),
atm_task_execution:stopping_reason()
) ->
boolean().
should_overwrite_stopping_reason(PrevReason, NewReason) ->
stopping_reason_priority(NewReason) > stopping_reason_priority(PrevReason).
@private
-spec stopping_reason_priority(atm_task_execution:stopping_reason()) ->
non_neg_integer().
stopping_reason_priority(pause) -> 0;
stopping_reason_priority(interrupt) -> 1;
stopping_reason_priority(failure) -> 2;
stopping_reason_priority(cancel) -> 3.
@private
-spec apply_diff(atm_task_execution:id(), atm_task_execution:diff()) ->
{ok, atm_task_execution:doc()} | {error, term()}.
apply_diff(AtmTaskExecutionId, Diff) ->
case atm_task_execution:update(AtmTaskExecutionId, Diff) of
{ok, AtmTaskExecutionDoc} = Result ->
handle_status_change(AtmTaskExecutionDoc),
Result;
{error, _} = Error ->
Error
end.
%%--------------------------------------------------------------------
@private
%% @doc
%% Updates atm task execution status stored in atm parallel box execution of
%% corresponding atm lane run if it was changed in task execution doc.
%%
%% NOTE: normally this should happen only after lane run processing has started
%% and concrete 'run_num' was set for all its tasks (it is not possible to
%% foresee what it will be beforehand as previous lane run may retried numerous
%% times). However, in case of failure/interruption during lane run preparation
%% after task execution documents have been created, this function will also
%% be called. Despite not having 'run_num' set there is no ambiguity to which
%% lane run it belongs as it can only happen to the newest run of given lane.
%% @end
%%--------------------------------------------------------------------
-spec handle_status_change(atm_task_execution:doc()) -> ok.
handle_status_change(#document{value = #atm_task_execution{status_changed = false}}) ->
ok;
handle_status_change(#document{
key = AtmTaskExecutionId,
value = #atm_task_execution{
workflow_execution_id = AtmWorkflowExecutionId,
lane_index = AtmLaneIndex,
run_num = RunNumOrUndefined,
parallel_box_index = AtmParallelBoxIndex,
status = NewStatus,
stopping_reason = StoppingReason,
status_changed = true
}
}) ->
RunSelector = utils:ensure_defined(RunNumOrUndefined, current),
ok = atm_lane_execution_status:handle_task_status_change(
AtmWorkflowExecutionId, {AtmLaneIndex, RunSelector}, AtmParallelBoxIndex,
AtmTaskExecutionId, StoppingReason, NewStatus
).
| null | https://raw.githubusercontent.com/onedata/op-worker/c3e0d43fb99da2f1e87f184d463a3119e5995538/src/modules/automation/task/atm_task_execution_status.erl | erlang | -------------------------------------------------------------------
@end
-------------------------------------------------------------------
@doc
This module contains functions that handle atm task execution status
transitions according (with some exceptions described below) to following
state machine:
|
v
------------------------------ +-----------+ <---- no item ever scheduled
/ | PENDING | \
| ------------------- +-----------+ \
| / | \ +----------+
| task execution stopped | resumed with ----- | RESUMING | --------
| with no item ever first item / +----------+ \
| scheduled to process scheduled to process / ^ |
| | / / | |
| | | ----------------------------- else | |
| | | / | |
| | | | ____ overriding | |
| | v v / \ ^stopping | |
| | +----------+ +------------+ / reason | |
| | | ACTIVE | ------ ^stopping -------> | STOPPING | <-- | |
| | +----------+ +------------+ | |
| | | / | |
| | task execution stopped --------- / |
| | with all items / resuming execution / |
| | processed | -----------------o----------- |
| | / \ | / | |
| | successfully else | / -------------|------- 4* ---- |
| | | | | / / | \ |
| v v v | / / | v |
| +-----------+ +----------+ +--------+ | +-------------+ +--------+ +-----------+ |
| | SKIPPED | | FINISHED | | FAILED | | | INTERRUPTED | <- 2* - | PAUSED | - 4* -> | CANCELLED | |
| +-----------+ +----------+ +--------+ | +-------------+ +--------+ +-----------+ |
| ^ | ^ ^ ^ |
| | | | | | |
| 1* | 2* 3* 4* |
| \ v | | / |
| [ task execution stopped due to ^stopping reason ] |
| ^ ^ |
\ / \ /
--------------------------------------------- --------------
It is necessary as results for already scheduled ones must be awaited even if no more items are scheduled.
In case when all items were already processed, such intermediate transition is omitted (transition
logically such transition occurs.
Possible reasons for ^stopping task execution when not all items were processed are as follows:
(e.g. error when processing uncorrelated results) or interruption of active task
if it has any uncorrelated results (some of them may have been lost).
has failed and entire automation workflow execution is being stopped.
@end
-------------------------------------------------------------------
API
===================================================================
API functions
===================================================================
Transition possible in case of race between resuming interrupted task and pausing it
Possible race condition when resuming and immediately pausing interrupted task (resuming
traverse hasn't yet transition task to RESUMING status while pausing traverse pauses it)
All jobs were executed but some must have failed
atm workflow execution may have been abruptly interrupted by e.g.
provider restart which resulted in stale `items_in_processing`
If task having uncorrelated results is interrupted not all of those
results may have been received and as such it is treated as failure
rather then interruption
Ensure status wasn't updated by parallel pause/interrupt (possible race)
in current incarnation
===================================================================
===================================================================
--------------------------------------------------------------------
@doc
Updates atm task execution status stored in atm parallel box execution of
corresponding atm lane run if it was changed in task execution doc.
NOTE: normally this should happen only after lane run processing has started
and concrete 'run_num' was set for all its tasks (it is not possible to
foresee what it will be beforehand as previous lane run may retried numerous
times). However, in case of failure/interruption during lane run preparation
after task execution documents have been created, this function will also
be called. Despite not having 'run_num' set there is no ambiguity to which
lane run it belongs as it can only happen to the newest run of given lane.
@end
-------------------------------------------------------------------- | @author
( C ) 2021 - 2022 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
Task transition to STOPPING status when execution is halted and not all items were processed .
from ACTIVE to stopped status can be done during one update operation ) - although
1 * - failure severe enough to cause stopping of entire automation workflow execution
2 * - abrupt interruption when some other component ( e.g task or external service like OpenFaaS )
3 * - user pausing entire automation workflow execution .
4 * - user cancelling entire automation workflow execution .
-module(atm_task_execution_status).
-author("Bartosz Walkowicz").
-include("modules/automation/atm_execution.hrl").
-export([is_transition_allowed/2, is_running/1]).
-export([
handle_items_in_processing/2,
handle_item_processed/1,
handle_items_withdrawn/2,
handle_items_failed/2,
handle_stopping/3,
handle_stopped/1,
handle_resuming/2,
handle_resumed/1
]).
-spec is_transition_allowed(atm_task_execution:status(), atm_task_execution:status()) ->
boolean().
is_transition_allowed(?PENDING_STATUS, ?SKIPPED_STATUS) -> true;
is_transition_allowed(?PENDING_STATUS, ?INTERRUPTED_STATUS) -> true;
is_transition_allowed(?PENDING_STATUS, ?PAUSED_STATUS) -> true;
is_transition_allowed(?PENDING_STATUS, ?CANCELLED_STATUS) -> true;
is_transition_allowed(?PENDING_STATUS, ?ACTIVE_STATUS) -> true;
is_transition_allowed(?ACTIVE_STATUS, ?FINISHED_STATUS) -> true;
is_transition_allowed(?ACTIVE_STATUS, ?FAILED_STATUS) -> true;
is_transition_allowed(?ACTIVE_STATUS, ?STOPPING_STATUS) -> true;
is_transition_allowed(?STOPPING_STATUS, ?FAILED_STATUS) -> true;
is_transition_allowed(?STOPPING_STATUS, ?INTERRUPTED_STATUS) -> true;
is_transition_allowed(?STOPPING_STATUS, ?PAUSED_STATUS) -> true;
is_transition_allowed(?STOPPING_STATUS, ?CANCELLED_STATUS) -> true;
is_transition_allowed(?PAUSED_STATUS, ?INTERRUPTED_STATUS) -> true;
is_transition_allowed(?PAUSED_STATUS, ?CANCELLED_STATUS) -> true;
( normally task should first transition to RESUMING status and only then to PAUSED )
is_transition_allowed(?INTERRUPTED_STATUS, ?PAUSED_STATUS) -> true;
is_transition_allowed(?INTERRUPTED_STATUS, ?CANCELLED_STATUS) -> true;
is_transition_allowed(?INTERRUPTED_STATUS, ?RESUMING_STATUS) -> true;
is_transition_allowed(?PAUSED_STATUS, ?RESUMING_STATUS) -> true;
is_transition_allowed(?RESUMING_STATUS, ?INTERRUPTED_STATUS) -> true;
is_transition_allowed(?RESUMING_STATUS, ?PAUSED_STATUS) -> true;
is_transition_allowed(?RESUMING_STATUS, ?CANCELLED_STATUS) -> true;
is_transition_allowed(?RESUMING_STATUS, ?PENDING_STATUS) -> true;
is_transition_allowed(?RESUMING_STATUS, ?ACTIVE_STATUS) -> true;
is_transition_allowed(_, _) -> false.
-spec is_running(atm_task_execution:status()) -> boolean().
is_running(?RESUMING_STATUS) -> true;
is_running(?PENDING_STATUS) -> true;
is_running(?ACTIVE_STATUS) -> true;
is_running(?STOPPING_STATUS) -> true;
is_running(_) -> false.
-spec handle_items_in_processing(atm_task_execution:id(), pos_integer()) ->
{ok, atm_task_execution:doc()} | {error, task_already_stopping} | {error, task_already_stopped}.
handle_items_in_processing(AtmTaskExecutionId, ItemCount) ->
apply_diff(AtmTaskExecutionId, fun
(AtmTaskExecution = #atm_task_execution{
status = ?PENDING_STATUS,
items_in_processing = 0
}) ->
{ok, AtmTaskExecution#atm_task_execution{
status = ?ACTIVE_STATUS,
items_in_processing = ItemCount
}};
(AtmTaskExecution = #atm_task_execution{
status = ?ACTIVE_STATUS,
items_in_processing = CurrentItemsInProcessingNum
}) ->
{ok, AtmTaskExecution#atm_task_execution{
items_in_processing = CurrentItemsInProcessingNum + ItemCount
}};
(#atm_task_execution{status = ?STOPPING_STATUS}) ->
{error, task_already_stopping};
(#atm_task_execution{status = Status}) when
Status =:= ?SKIPPED_STATUS;
Status =:= ?INTERRUPTED_STATUS;
Status =:= ?PAUSED_STATUS;
Status =:= ?FINISHED_STATUS;
Status =:= ?FAILED_STATUS;
Status =:= ?CANCELLED_STATUS
->
{error, task_already_stopped}
end).
-spec handle_item_processed(atm_task_execution:id()) -> ok.
handle_item_processed(AtmTaskExecutionId) ->
{ok, _} = apply_diff(AtmTaskExecutionId, fun(#atm_task_execution{
items_in_processing = ItemsInProcessing,
items_processed = ItemsProcessed
} = AtmTaskExecution) ->
{ok, AtmTaskExecution#atm_task_execution{
items_in_processing = ItemsInProcessing - 1,
items_processed = ItemsProcessed + 1
}}
end),
ok.
-spec handle_items_withdrawn(atm_task_execution:id(), pos_integer()) ->
{ok, atm_task_execution:doc()} | {error, task_not_stopping}.
handle_items_withdrawn(AtmTaskExecutionId, ItemCount) ->
apply_diff(AtmTaskExecutionId, fun
(AtmTaskExecution = #atm_task_execution{
status = ?STOPPING_STATUS,
items_in_processing = ItemsInProcessing
}) ->
{ok, AtmTaskExecution#atm_task_execution{
items_in_processing = ItemsInProcessing - ItemCount
}};
(_) ->
{error, task_not_stopping}
end).
-spec handle_items_failed(atm_task_execution:id(), pos_integer()) -> ok.
handle_items_failed(AtmTaskExecutionId, ItemCount) ->
{ok, _} = apply_diff(AtmTaskExecutionId, fun(#atm_task_execution{
items_in_processing = ItemsInProcessing,
items_processed = ItemsProcessed,
items_failed = ItemsFailed
} = AtmTaskExecution) ->
{ok, AtmTaskExecution#atm_task_execution{
items_in_processing = ItemsInProcessing - ItemCount,
items_processed = ItemsProcessed + ItemCount,
items_failed = ItemsFailed + ItemCount
}}
end),
ok.
-spec handle_stopping(
atm_task_execution:id(),
atm_task_execution:stopping_reason(),
atm_workflow_execution:incarnation()
) ->
{ok, atm_task_execution:doc()} | {error, task_already_stopping} | {error, task_already_stopped}.
handle_stopping(AtmTaskExecutionId, Reason, CurrentIncarnation) ->
apply_diff(AtmTaskExecutionId, fun
(AtmTaskExecution = #atm_task_execution{status = Status}) when
Status =:= ?PENDING_STATUS;
Status =:= ?RESUMING_STATUS
->
{ok, AtmTaskExecution#atm_task_execution{
status = infer_stopped_status(Reason),
stopping_incarnation = CurrentIncarnation
}};
(AtmTaskExecution = #atm_task_execution{status = ?ACTIVE_STATUS}) ->
{ok, AtmTaskExecution#atm_task_execution{
status = ?STOPPING_STATUS,
stopping_reason = Reason,
stopping_incarnation = CurrentIncarnation
}};
(AtmTaskExecution = #atm_task_execution{
status = ?STOPPING_STATUS,
stopping_reason = PrevReason
}) ->
case should_overwrite_stopping_reason(PrevReason, Reason) of
true -> {ok, AtmTaskExecution#atm_task_execution{stopping_reason = Reason}};
false -> {error, task_already_stopping}
end;
(AtmTaskExecution = #atm_task_execution{status = ?PAUSED_STATUS}) when
Reason =:= cancel;
Reason =:= interrupt
->
{ok, AtmTaskExecution#atm_task_execution{
status = infer_stopped_status(Reason),
stopping_reason = Reason,
stopping_incarnation = CurrentIncarnation
}};
(AtmTaskExecution = #atm_task_execution{
status = ?INTERRUPTED_STATUS,
stopping_incarnation = PrevStoppingIncarnation
}) when
Reason =:= cancel;
(Reason =:= pause andalso PrevStoppingIncarnation < CurrentIncarnation)
->
{ok, AtmTaskExecution#atm_task_execution{
status = infer_stopped_status(Reason),
stopping_reason = Reason,
stopping_incarnation = CurrentIncarnation
}};
(#atm_task_execution{status = Status}) when
Status =:= ?SKIPPED_STATUS;
Status =:= ?INTERRUPTED_STATUS;
Status =:= ?PAUSED_STATUS;
Status =:= ?FINISHED_STATUS;
Status =:= ?FAILED_STATUS;
Status =:= ?CANCELLED_STATUS
->
{error, task_already_stopped}
end).
-spec handle_stopped(atm_task_execution:id()) ->
{ok, atm_task_execution:doc()} | {error, task_already_stopped}.
handle_stopped(AtmTaskExecutionId) ->
apply_diff(AtmTaskExecutionId, fun
(AtmTaskExecution = #atm_task_execution{status = ?PENDING_STATUS}) ->
{ok, AtmTaskExecution#atm_task_execution{status = ?SKIPPED_STATUS}};
(AtmTaskExecution = #atm_task_execution{
status = ?ACTIVE_STATUS,
items_in_processing = 0,
items_failed = 0
}) ->
{ok, AtmTaskExecution#atm_task_execution{status = ?FINISHED_STATUS}};
(AtmTaskExecution = #atm_task_execution{
status = ?ACTIVE_STATUS,
items_in_processing = 0
}) ->
{ok, AtmTaskExecution#atm_task_execution{status = ?FAILED_STATUS}};
(AtmTaskExecution = #atm_task_execution{
status = ?STOPPING_STATUS,
stopping_reason = StoppingReason,
items_in_processing = ItemsInProcessing,
items_processed = ItemsProcessed,
items_failed = ItemsFailed,
uncorrelated_result_specs = UncorrelatedResultSpecs
}) ->
UpdatedProcessedItems = ItemsProcessed + ItemsInProcessing,
UpdatedFailedItems = ItemsFailed + ItemsInProcessing,
{ok, AtmTaskExecution#atm_task_execution{
status = case {StoppingReason, lists_utils:is_empty(UncorrelatedResultSpecs)} of
{interrupt, false} ->
?FAILED_STATUS;
_ ->
infer_stopped_status(StoppingReason)
end,
items_in_processing = 0,
items_processed = UpdatedProcessedItems,
items_failed = UpdatedFailedItems
}};
(#atm_task_execution{status = Status}) when
Status =:= ?SKIPPED_STATUS;
Status =:= ?INTERRUPTED_STATUS;
Status =:= ?PAUSED_STATUS;
Status =:= ?FINISHED_STATUS;
Status =:= ?FAILED_STATUS;
Status =:= ?CANCELLED_STATUS
->
{error, task_already_stopped}
end).
-spec handle_resuming(atm_task_execution:id(), atm_workflow_execution:incarnation()) ->
{ok, atm_task_execution:doc()} | {error, task_already_stopped}.
handle_resuming(AtmTaskExecutionId, CurrentIncarnation) ->
apply_diff(AtmTaskExecutionId, fun
(AtmTaskExecution = #atm_task_execution{
status = Status,
stopping_incarnation = PrevStoppingIncarnation
}) when
(Status =:= ?INTERRUPTED_STATUS orelse Status =:= ?PAUSED_STATUS),
PrevStoppingIncarnation < CurrentIncarnation
->
{ok, AtmTaskExecution#atm_task_execution{
status = ?RESUMING_STATUS,
stopping_reason = undefined
}};
(#atm_task_execution{status = Status}) when
Status =:= ?SKIPPED_STATUS;
Status =:= ?INTERRUPTED_STATUS;
Status =:= ?PAUSED_STATUS;
Status =:= ?FINISHED_STATUS;
Status =:= ?FAILED_STATUS;
Status =:= ?CANCELLED_STATUS
->
{error, task_already_stopped}
end).
-spec handle_resumed(atm_task_execution:id()) ->
{ok, atm_task_execution:doc()} | {error, task_already_stopped}.
handle_resumed(AtmTaskExecutionId) ->
apply_diff(AtmTaskExecutionId, fun
(AtmTaskExecution = #atm_task_execution{
status = ?RESUMING_STATUS,
items_in_processing = 0,
items_processed = 0,
items_failed = 0
}) ->
{ok, AtmTaskExecution#atm_task_execution{status = ?PENDING_STATUS}};
(AtmTaskExecution = #atm_task_execution{status = ?RESUMING_STATUS}) ->
{ok, AtmTaskExecution#atm_task_execution{status = ?ACTIVE_STATUS}};
(#atm_task_execution{status = Status}) when
Status =:= ?SKIPPED_STATUS;
Status =:= ?INTERRUPTED_STATUS;
Status =:= ?PAUSED_STATUS;
Status =:= ?FINISHED_STATUS;
Status =:= ?FAILED_STATUS;
Status =:= ?CANCELLED_STATUS
->
{error, task_already_stopped}
end).
Internal functions
@private
-spec infer_stopped_status(atm_task_execution:stopping_reason()) -> atm_task_execution:status().
infer_stopped_status(pause) -> ?PAUSED_STATUS;
infer_stopped_status(interrupt) -> ?INTERRUPTED_STATUS;
infer_stopped_status(failure) -> ?FAILED_STATUS;
infer_stopped_status(cancel) -> ?CANCELLED_STATUS.
@private
-spec should_overwrite_stopping_reason(
atm_task_execution:stopping_reason(),
atm_task_execution:stopping_reason()
) ->
boolean().
should_overwrite_stopping_reason(PrevReason, NewReason) ->
stopping_reason_priority(NewReason) > stopping_reason_priority(PrevReason).
@private
-spec stopping_reason_priority(atm_task_execution:stopping_reason()) ->
non_neg_integer().
stopping_reason_priority(pause) -> 0;
stopping_reason_priority(interrupt) -> 1;
stopping_reason_priority(failure) -> 2;
stopping_reason_priority(cancel) -> 3.
@private
-spec apply_diff(atm_task_execution:id(), atm_task_execution:diff()) ->
{ok, atm_task_execution:doc()} | {error, term()}.
apply_diff(AtmTaskExecutionId, Diff) ->
case atm_task_execution:update(AtmTaskExecutionId, Diff) of
{ok, AtmTaskExecutionDoc} = Result ->
handle_status_change(AtmTaskExecutionDoc),
Result;
{error, _} = Error ->
Error
end.
@private
-spec handle_status_change(atm_task_execution:doc()) -> ok.
handle_status_change(#document{value = #atm_task_execution{status_changed = false}}) ->
ok;
handle_status_change(#document{
key = AtmTaskExecutionId,
value = #atm_task_execution{
workflow_execution_id = AtmWorkflowExecutionId,
lane_index = AtmLaneIndex,
run_num = RunNumOrUndefined,
parallel_box_index = AtmParallelBoxIndex,
status = NewStatus,
stopping_reason = StoppingReason,
status_changed = true
}
}) ->
RunSelector = utils:ensure_defined(RunNumOrUndefined, current),
ok = atm_lane_execution_status:handle_task_status_change(
AtmWorkflowExecutionId, {AtmLaneIndex, RunSelector}, AtmParallelBoxIndex,
AtmTaskExecutionId, StoppingReason, NewStatus
).
|
d6985997825250b1843afd9e4bc53e2a1a8d14f71554d421b9b3db5a1106a292 | racket/compatibility | zip.rkt | #lang racket/base
;; deprecated library, see `file/zip`
(require file/zip)
(provide (all-from-out file/zip))
| null | https://raw.githubusercontent.com/racket/compatibility/492030dac6f095045ce8a13dca75204dd5f34e32/compatibility-lib/mzlib/zip.rkt | racket | deprecated library, see `file/zip` | #lang racket/base
(require file/zip)
(provide (all-from-out file/zip))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.