What are functors, and why do we need them? - functor

I don't understand Factor's functors. I guess it would help to first understand what a "functor" is.
Google says:
a function; an operator.
In Factor, all functions (words) are operators, and are first-class. (In fact, I can't think of much in Factor that isn't first class). This definition isn't so helpful.
Wikipedia says:
Functor may refer to:
...
In computer programming:
function object used to pass function pointers along with its state
...
In Haskell a Functor describes a generalisation of functions that perform mapping operations
The page for "function object" says:
an object to be invoked or called as if it were an ordinary function, usually with the same syntax (a function parameter that can also be a function).
So a functor is a first-class function? This is nothing special, and anyways words and quotations and stuff are already first-class in Factor.
Factor Functors have weird syntax that reminds me of generics or something.
resource:unmaintained/models/combinators/templates/templates.factor:
FROM: models.combinators => <collection> #1 ;
FUNCTOR: fmaps ( W -- )
W IS ${W}
w-n DEFINES ${W}-n
w-2 DEFINES 2${W}
w-3 DEFINES 3${W}
w-4 DEFINES 4${W}
w-n* DEFINES ${W}-n*
w-2* DEFINES 2${W}*
w-3* DEFINES 3${W}*
w-4* DEFINES 4${W}*
WHERE
MACRO: w-n ( int -- quot ) dup '[ [ _ narray <collection> ] dip [ _ firstn ] prepend W ] ;
: w-2 ( a b quot -- mapped ) 2 w-n ; inline
: w-3 ( a b c quot -- mapped ) 3 w-n ; inline
: w-4 ( a b c d quot -- mapped ) 4 w-n ; inline
MACRO: w-n* ( int -- quot ) dup '[ [ _ narray <collection> #1 ] dip [ _ firstn ] prepend W ] ;
: w-2* ( a b quot -- mapped ) 2 w-n* ; inline
: w-3* ( a b c quot -- mapped ) 3 w-n* ; inline
: w-4* ( a b c d quot -- mapped ) 4 w-n* ; inline
;FUNCTOR
The documentation is extremely sparse on these. What are they? When should I use them?

Don't think of functors as that 'They're named "functors" to annoy category theory fanboys and language purists.' :)
Their use is mainly to generate boilerplate or template code. Just like C++ templates are an optimization feature because generic dispatch can be slow, so are Factor functors.
Example here:
USING: functors io lexer namespaces ;
IN: examples.functors
FUNCTOR: define-table ( NAME -- )
name-datasource DEFINES-CLASS ${NAME}-datasource
clear-name DEFINES clear-${NAME}
init-name DEFINES init-${NAME}
WHERE
SINGLETON: name-datasource
: clear-name ( -- ) "clear table code here" print ;
: init-name ( -- ) "init table code here" print ;
name-datasource [ "hello-hello" ] initialize
;FUNCTOR
SYNTAX: SQL-TABLE: scan-token define-table ;
You can now write SQL-TABLE: person and Factor will create the words clear-person, init-person and person-datasource for you.
When to use them? I think never unless you have performance problems that warrants their use. They are very bad for grepability.

Related

How do I sort an array of nested types?

I have the following data structure in Fortran 95:
type :: timestamp_record
integer :: year
integer :: month
integer :: day
integer :: hour
integer :: minute
integer :: second
end type
​
type :: foo_record
type(timestamp_record) :: timestamp
integer :: foo
integer :: bar
integer :: baz
end type
​
type(foo_record),dimension(10000) :: my_array
​
I want to sort my_array by:
timestamp%year
timestamp%month
timestamp%day
timestamp%hour
timestamp%minute
timestamp%second
I have seen that there are qsort and qsort64 available, but I do not understand what shall I use as length.
Also I see that there is a need to provide the comparison function (similar to C qsort).
Three questions:
Where can I find an example of qsort implemented for two or three fields?
Can I use it even for this case where I want to sort an array of nested types?
Are type structures called struct in Fortran?
I cannot comment on where you find an example code. That is off-topic here, but examples do exist. Use we search. Try sites like Github or RosettaCode.
However, it is good to note how structures are typically sorted. You most often create a comparison function that compares two object and says how should they be order, which of them should go first.
For example, from my code
function CompareWMPoints(Aptr,Bptr) bind(C,name="CompareWMPoints") result(res)
use iso_c_binding
integer(c_int) :: res
type(c_ptr),value :: Aptr,Bptr
type(WMPoint),pointer :: A,B
call c_f_pointer(Aptr,A)
call c_f_pointer(Bptr,B)
if ((A%xi+(A%yj-1)*Prnx+(A%zk-1)*Prnx*Prny) < (B%xi+(B%yj-1)*Prnx+(B%zk-1)*Prnx*Prny)) then
res = -1_c_int
else if ((A%xi+(A%yj-1)*Prnx+(A%zk-1)*Prnx*Prny) > (B%xi+(B%yj-1)*Prnx+(B%zk-1)*Prnx*Prny)) then
res = 1_c_int
else if (A%distx**2+A%disty**2+A%distz**2 < B%distx**2+B%disty**2+B%distz**2) then
res = -1_c_int
else if (A%distx**2+A%disty**2+A%distz**2 > B%distx**2+B%disty**2+B%distz**2) then
res = 1_c_int
else
res = 0_c_int
end if
end function CompareWMPoints
This compares two objects, A and B. You can reference any other structure that is nested inside these two objects. The result of the comparison is an integer (-1, 1 or 0).
Note: A and B are passed through C pointers because the C qsort() is used. That is avoided by using a Fortran sorting subroutine. One could use type(...), intent(in) :: but that is not legal if the type is not interoperable.
Because I am lazy I just call the qsort() from the C standard library
interface
subroutine qsort(array,elem_count,elem_size,compare) bind(C,name="qsort")
import
type(c_ptr),value :: array
integer(c_size_t),value :: elem_count
integer(c_size_t),value :: elem_size
type(c_funptr),value :: compare !int(*compare)(const void *, const void *)
end subroutine qsort !standard C library qsort
end interface
but you can call any other subroutine that uses comparison functions.
There is a certain performance penalty that comes from using these callback functions but it is often not that important.

Inline records in polymorphic variants?

The ocaml manual chapter 8 "language extensions" describes "inline records" (8.17):
The arguments of sum-type constructors can now be defined using the same syntax as records. Mutable and polymorphic fields are allowed. GADT syntax is supported. Attributes can be specified on individual fields. [...]
I am looking for that with polymorphic variants:
# type a = B of {x:int; mutable y:int} ;;
type a = B of { x : int; mutable y : int; }
# type b = `A of {u:int; mutable v:int} ;;
Line 1, characters 9-10:
Error: Syntax error
But that does not work, so right now I use an explicit auxiliary record type instead...
As I understand it now, this both takes more memory and is somewhat slower.
Can I get this cool feature with polymorphic variants, too?
In the cases of ordinary constructors, the compiler can use the type definition to distinguish between:
type t = A of int * int | B
let f = function
| A (_,y) -> y
| B -> 0
and
type 'a t = A of 'a | B
let f = function
| A (_,y) -> y
| B -> 0
Thus, it is possible to optimize the first
A (_,y) -> y
into "access the second field of the block` while still compiling the second case
A (_,y) -> y
to "access the tuple in the first field of the block, and then access the second field of the block".
For polymorphic variants, it is not possible to rely on the non-existing type definition to distinguish between those two solutions. Consequently, their memory representation must be uniform. This means that polymorphic variants always take one argument, and it is not really useful to label each argument of the constructor when there is only one argument.
This is why inline records cannot be combined with polymorphic variants.

Compile an anonymous word in a compiled word

I'm currently working on a small interpreter written in Forth. For a small optimization, I'm trying to have a word which creates compiled words. For example, something which behaves like this:
: creator ( -- a )
:noname ( u -- u )
10 + ;
;
10 creator execute .
>> 20 ok
I tried several approaches so far and non worked (naïve like above, switching in interpretive mode, trying to compile a string of Forth source). Is this actually possible?
When you write compiling words, you have to be very careful about which words execute at compile time, and which execute at runtime. In this case, 10 + runs at compile time, and will not be compiled into you :noname definition.
I believe this is what you want:
: creator ( -- xt ) :noname ( n1 -- n2 )
10 postpone literal postpone + postpone ; ;
Also note that you may use CREATE DOES> in many cases. E.g. if you want your creator to accept a number which is used by the child word:
: creator ( n1 "name" -- ) create ,
does> ( n2 -- n1+n2 ) # + ;

How to call a constructed quotation in Factor

I have a word which constructs a quotation which I want to be called. However, when I load the code I get Cannot apply “call” to a run-time computed value. If I use the walker and step thru the code it executes as expected. How are you supposed to call a constructed quotation?
: ba>struct ( array class -- struct array )
[ <struct> swap ] keep struct-slots
[
[ type>> to-type ] keep
name>> setter-word 1quotation curry
[ over ] dip curry call drop
] each
;
EDITED: This does work
: ba>struct ( array class -- struct array )
[ <struct> swap ] keep struct-slots
[
[ type>> to-type ] keep
name>> setter-word 1quotation curry
[ over ] dip curry call( -- x ) drop
] each
;
The problem stems from the runtime not knowing what the stack effect is of a constructed quote. In these cases, you must declare what the stack looks like to the quote for the call.

Haskell - Redefining (hiding) arithmetic operators

I want to redefine several arithmetic operators in Haskell in order to make them more extensible and generic.
E.g.
class Mul a b c | a b -> c where
(*) :: a -> b -> c
This seems to work in combination with
import Prelude hiding ((*))
hiding the standard * operator. But of course all usual multiplications have to work as well, so I'd have to define something like
instance (Num t) => Mul t t t where
(*) = ??
How can I access the original * operator (Prelude.(*) doesn't work) here and how do I have to define the instance type such that 1 * 1 doesn't conflict with the Monomorpism Restriction?
Edit -
import qualified
is a good tip, thanks.
But unfortunately this forced me to bring all standard methods into scope explicitly. I just want to have the possibility of redefining certain bindings leaving the rest unchanged.
So is there a combination of both? Something like
import Prelude qualified ((*))
Answering the edited question:
You can do
import Prelude hiding ((*))
import qualified Prelude as P
to gain access to all Prelude functions except (*) in the usual way and to (*) via the P prefix:
x = 5 + 3 -- works
y = 5 P.* 3 -- works
z = 5 * 3 -- complains about * not being in scope
The instance
instance (Num t) => Mul t t t where
(*) = ??
Will largely defeat the purpose of having defined Mul t t t in the first place, without abusing extensions to allow {-# LANGUAGE OverlappingInstances #-}.
Unfortunately the 'right' if painful answer is to go through instance by instance and do
import Prelude hiding ((*))
import qualified Prelude
instance Mul Int Int Int where
(*) = (Prelude.*)
instance Mul Double Double Double where
(*) = (Prelude.*)
instance Mul Int Double Double where
...
instance Mul (Complex Float) (Complex Double) (Complex Double)
...
Otherwise the way that instance heads get resolved in the compiler (no backtracking is done) will probably make your novel instances cause compilation to blow up when you go to actually use them.
That said, you can at least ease the pain for instances you didn't think of:
newtype Other a = Other a
instance Num a => Mul (Other a) (Other a) (Other a) where
Other a * Other b = Other (a Prelude.* b)
This will at least let them just use your newtype wrapper if they don't want to go and define Mul and all of your other classes themselves.
There have been a few attempts to do things like this.
Firstly,
How can I access the original * operator (Prelude.(*) doesn't work)
You'll need to:
import qualified Prelude
now you can use e.g. (Prelude.*). This is less aggressive than "LANGUAGE NoImplicitPrelude" which will also cause local uses of >>= and so on to be rebound to your definitions.
Here are examples of other people's alternative preludes:
http://hackage.haskell.org/package/prelude-plus -- a simpler prelude (?)
http://hackage.haskell.org/package/numeric-prelude -- an alternative numerical hierarchy.
I can answer the first question. Hiding the (*) operator really hides it, so you can't get at it. However, you can import Prelude qualified:
import qualified Prelude as P
foo = 3 P.* 14 -- == 42
I think that that does what you want.

Resources