/utils/utils.factor

http://github.com/mrjbq7/re-factor · Factor · 87 lines · 69 code · 16 blank · 2 comment · 13 complexity · ff094d6d69225aafd2c99ad6c9a98872 MD5 · raw file

  1. ! Copyright (C) 2011 John Benediktsson
  2. ! See http://factorcode.org/license.txt for BSD license
  3. USING: accessors arrays assocs combinators fry generic
  4. io.pathnames kernel lexer math math.functions math.order
  5. math.parser math.private namespaces parser random sequences
  6. sorting source-files tools.annotations ;
  7. IN: utils
  8. SYNTAX: =>
  9. unclip-last scan-object 2array suffix! ;
  10. <PRIVATE
  11. : (include) ( parsed name -- parsed )
  12. [ file get path>> parent-directory ] dip
  13. ".factor" append append-path parse-file append ;
  14. PRIVATE>
  15. SYNTAX: INCLUDE: scan-token (include) ;
  16. SYNTAX: INCLUDING: ";" [ (include) ] each-token ;
  17. : trim-histogram ( assoc n -- alist )
  18. [ sort-values reverse ] [ cut ] bi* values sum
  19. [ "Other" swap 2array suffix ] unless-zero ;
  20. : humanize ( n -- str )
  21. dup 100 mod 11 13 between? [ "th" ] [
  22. dup 10 mod {
  23. { 1 [ "st" ] }
  24. { 2 [ "nd" ] }
  25. { 3 [ "rd" ] }
  26. [ drop "th" ]
  27. } case
  28. ] if [ number>string ] [ append ] bi* ;
  29. <<
  30. : wrap-method ( word before-quot after-quot -- )
  31. pick reset [ surround ] 2curry annotate ;
  32. >>
  33. <<
  34. SYNTAX: BEFORE:
  35. scan-word scan-word lookup-method
  36. parse-definition [ ] wrap-method ;
  37. SYNTAX: AFTER:
  38. scan-word scan-word lookup-method
  39. [ ] parse-definition wrap-method ;
  40. >>
  41. : (count-digits) ( n m -- n' )
  42. {
  43. { [ dup 10 < ] [ drop ] }
  44. { [ dup 100 < ] [ drop 1 fixnum+fast ] }
  45. { [ dup 1000 < ] [ drop 2 fixnum+fast ] }
  46. { [ dup 1000000000000 < ] [
  47. dup 100000000 < [
  48. dup 1000000 < [
  49. dup 10000 < [
  50. drop 3
  51. ] [
  52. 100000 >= 5 4 ?
  53. ] if
  54. ] [
  55. 10000000 >= 7 6 ?
  56. ] if
  57. ] [
  58. dup 10000000000 < [
  59. 1000000000 >= 9 8 ?
  60. ] [
  61. 100000000000 >= 10 9 ?
  62. ] if
  63. ] if fixnum+fast
  64. ] }
  65. [ [ 12 fixnum+fast ] [ 1000000000000 /i ] bi* (count-digits) ]
  66. } cond ; inline recursive
  67. GENERIC: count-digits ( m -- n )
  68. M: fixnum count-digits 1 swap (count-digits) ;
  69. M: bignum count-digits 1 swap (count-digits) ;
  70. : count-digits2 ( num radix -- n )
  71. [ log ] [ log ] bi* /i 1 + ; inline