Skip to content

Instantly share code, notes, and snippets.

@toomasv
Last active March 25, 2020 12:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toomasv/d22ebd000ff34012996df62106c275e2 to your computer and use it in GitHub Desktop.
Save toomasv/d22ebd000ff34012996df62106c275e2 to your computer and use it in GitHub Desktop.
Return relation of provided arguments
Red [
Description: {Return relation of provided arguments}
Date: 25-Mar-2020
Author: "Tooams Vooglaid"
]
compare: function [
"Compare arguments and return their relation"
a [any-type!]
b [any-type!]
/length "Compare length of arguments"
/sum "Compare sum of arguments"
/with "Compare arguments by provided function"
fn [any-function! block!]
/long "Return longer prefix comparator instead of short operator"
][
;By default arguments are compared by their value (strings by sorting value)
;If refinements are given, arguments are compared by provided function(s).
;If `fn` is a block, it is assumed to be body of the function with one argument, named `_`.
case [
length [
with: yes
fn: :length?
]
sum [
with: yes
fn: :system/words/sum
]
]
if with [
if block? :fn [
fn: func [_] fn
]
a: fn a
b: fn b
]
out: case [
a > b ['>]
a < b ['<]
a = b ['=]
]
either long [select [> greater? = equal? < lesser?] out][out]
]
comment [
;Sorting order
compare "abcdegftreghyue" "abcdeghtregyh"
; <
;Value
compare 1324567234 1324756918
; <
compare #"¤" #"£"
; >
;Length
compare/length "abcdegftreghyue" "abcdeghtregyh"
; >
compare/length "abcdegftreghyue" "lkjdlkfjsd fksj"
; =
;Sum
compare/sum [1 2 3 4 5 6 7 8 9][6 5 4 7 3 3 9 8 0]
; =
;Simple func
compare/with [0 1 2 3 4 5 6 7 8 9][6 5 4 7 3 2 9 8 1] :sum
; =
compare/with [0 1 2 3 4 5 6 7 8 9][6 5 4 7 3 2 9 8 1] :length?
; >
;Function body
compare/with [1 2 3 4 5 6 7 8 9][6 5 4 7 3 2 9 8 1] [fifth _]
; >
compare/with [0 1 2 3 4 5 6 7 8 9][6 5 4 7 3 2 9 8 1][(_/5) ** (_/4)]
; <
compare/with true false [make integer! _]
; >
;Different properties
compare sum [0 1 2 3 4 5 6 7] length? "Is this sentence? longer that sum of previous block?"
; <
;Return long comparator
compare/with/long true false [make integer! _]
; greater?
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment