Related
For instance, how can I write something in ATS corresponding to the following code in C:
void myloop(int n)
{
int i;
for (i = 0; i < n; i += 1) printf("i = %i\n", i);
return;
}
One can replicate this in a way that's remarkably close to the C version:
fun myloop (n: int): void = let
var i: int
in
for (i := 0; i < n; i := i + 1) begin
println! ("i = ", i)
end
end
A minor caveat: As far as I know, there is no format string support in print and println.
If you like combinators, try this one
//
staload "share/atspre_staload.hats"
staload "share/HATS/atspre_staload_libats_ML.hats"
//
fun myloop(n: int): void =
(n).foreach()(lam i => $extfcall(void, "printf", "i = %i\n", i))
//
When compiling the code, you need the flag -DATS_MEMALLOC_LIBC. You can try the code here:
https://glot.io/snippets/ejjr3j1pil
The standard way to do this in functional programming is to implement a tail-recursive function:
fun myloop
(n: int): void = let
fun myloop2
(n: int, i: int): void =
if i < n then (println! ("i = ", i); myloop2(n, i+1)) else ()
// end of [myloop2]
in
myloop2(n, 0)
end // end of [myloop]
This is more a kind of theoretical question. Is it possible in C++11 to combine functions into a new function? For example :
auto f = [](int i){return i * 2;};
auto g = [](int i){return i + 10;};
So this works:
auto c = f(g(20)); // = 60
But I want an object that stores the combination, like
auto c = f(g);
std::cout << c(20) << std::endl; //prints 60
Edit:
Additionally what i want to create is a function a, which you can give a function b and an int n, and which returns the n'th combination of the given function b. For example (not compilable)
template<typename T>
auto combine(T b, int i) -> decltype(T)
{
if (i == 0)
return b;
return combine(b, i - 1);
}
auto c = combine(f, 2); //c = f(f(f(int)))
A first attempt:
template<class First, class Second>
auto compose( Second&& second, First&& first ) }
return [second = std::forward<Second>(second), first=std::forward<First>(first)]
(auto&&...args)->decltype(auto) {
return second( first( decltype(args)(args)... ) );
};
}
template<class A, class B, class...Rest>
auto compose(A&& a, B&& b, Rest&&... rest) {
return compose( compose(std::forward<A>(a), std::forward<B>(b)), std::forward<Rest>(rest)... );
}
template<class A>
std::decay_t<A> compose(A&& a) {
return std::forward<A>(a);
}
in C++14. Now, this isn't perfect, as the pattern doesn't work all that well in C++.
To do this perfectly, we'd have to take a look at compositional programming. Here, functions interact with an abstract stack of arguments. Each function pops some number of arguments off the stack, then pops some number back on.
This would allow you do do this:
compose( print_coord, get_x, get_y )
where get_x and get_y consume nothing but return a coordinate, and print_coord takes two coordinates and prints them.
To emulate this in C++, we need some fancy machinery. Functions will return tuples (or tuple-likes?), and those values will be "pushed onto the argument stack" logically.
Functions will also consume things off this argument stack.
At each invocation, we unpack the current tuple of arguments, find the longest collection that the function can be called with, call it, get its return value, unpack it if it is a tuple, and then stick any such returned values back on the argument stack.
For this more advanced compose to compose with itself, it then needs SFINAE checks, and it needs to be able to take a invokable object and a tuple of arguments and find the right number of arguments to call the invokable object with, plus the left-over arguments.
This is a tricky bit of metaprogramming that I won't do here.
The second part, because I missed it the first time, looks like:
template<class F>
auto function_to_the_power( F&& f, unsigned count ) {
return [f=std::forward<F>(f),count](auto&& x)
-> std::decay_t< decltype( f(decltype(x)(x)) ) >
{
if (count == 0) return decltype(x)(x);
auto r = f(decltype(x)(x));
for (unsigned i = 1; i < count; ++i) {
r = f( std::move(r) );
}
return r;
};
}
This uses no type erasure.
Test code:
auto f = [](int x){ return x*3; };
auto fs = std::make_tuple(
function_to_the_power( f, 0 ),
function_to_the_power( f, 1 ),
function_to_the_power( f, 2 ),
function_to_the_power( f, 3 )
);
std::cout << std::get<0>(fs)(2) << "\n";
std::cout << std::get<1>(fs)(2) << "\n";
std::cout << std::get<2>(fs)(2) << "\n";
std::cout << std::get<3>(fs)(2) << "\n";
prints:
2
6
18
54
You can write something along the lines of:
#include <functional>
#include <iostream>
template<class F>
F compose(F f, F g)
{
return [=](int x) { return f(g(x)); };
}
int main()
{
std::function<int (int)> f = [](int i) { return i * 2; };
std::function<int (int)> g = [](int i) { return i + 10; };
auto c = compose(f, g);
std::cout << c(20) << '\n'; // prints 60
}
The code can be simply extended to cover the second half of the question:
template<class F>
F compose(F f, unsigned n)
{
auto g = f;
for (unsigned i = 0; i < n; ++i)
g = compose(g, f);
return g;
}
int main()
{
std::function<int (int)> h = [](int i) { return i * i; };
auto d = compose(h, 1);
auto e = compose(h, 2);
std::cout << d(3) << "\n" // prints 81
<< e(3) << "\n"; // prints 6561
}
NOTE. Here using std::function. It isn't a lambda but wraps a lambda with a performance cost.
This code doesn't compile, I don't get why:
struct C { int a;};
void foo(C c, int s)
{
cout << c.a << s;
}
int main()
{
std::function<void(C,int)> call = std::bind(&foo,std::placeholders::_1,5);
C c;
c.a = 5;
call(c);
return 0;
}
I get:
No match for call to std::function<void(C,int)> (C&)
The bind() expression std::bind(&foo, _1, 5) produces a unary function. You try to use a unary function to initialize a binary std::function<void(c, int)>. Did you mean to use something like this?
std::function<void(C)> call = std::bind(&foo, _1, 5);
Let's say I want to calculate the following:
A/Z
Where A is of length 128 bit and Z is 64 bit long. A is stored in 2 64 bit registers since the registers of the system can store up to 64 bits. What would be an efficient way to calculate the result?
P.S: I've solved similar multiplication problems by using CSD representations. However, this would require calculating 1/Z first.
The right way to solve such a problem, is by returning to the basics:
divide the most significant register by the denominator
calculate the quotient Q and the rest R
define a new temporary register preferrably with the same length as the other 2
the rest should occupy the most significant bits in the temporary register
shift the lesser significant register to the right by the same amount of bits contained iR and add to the result to the temporary register.
go back to step 1
after the division, the resulting rest must be casted to double, divided by the denominator then added to the quotient.
[Edit1] spotted bug repaired
I assume you want integer division so here is the math for 8bit analogy:
A = { a0 + (a1<<8) }
D = { d0 + (d1<<8) } ... division result
Z = { z0 }
D = (a0/z0) + ((a1*256)/z0) + (( (a0%z0) + ((a1*256)%z0) )/z0);
D = (a0/z0) + ((a1/z0)*256) + ((a1%z0)*(256/z0)) + (( (a0%z0) + ((a1%z0)*(256%z0)) )/z0);
Now the terms 256/z0 and 256%z0 can be computed like this (C++):
i0=0xFF/z0; if ((z0&(z0-1))==0) i0++; // i0 = 256/z0
i1=i0*z0; i1^=0xFF; i1++; // i1 = 256%z0
So the i0 is just incremented in case the z0 is power of 2, and i1 is just remainder computed from the division.
a/b = d + r/b
r = a - a*d
Here tested 8bit code:
//---------------------------------------------------------------------------
// unsigned 8 bit ALU in C++
//---------------------------------------------------------------------------
BYTE cy; // carry flag cy = { 0,1 }
void inc(BYTE &a); // a++
void dec(BYTE &a); // a--
void add(BYTE &c,BYTE a,BYTE b); // c = a+b
void adc(BYTE &c,BYTE a,BYTE b); // c = a+b+cy
void sub(BYTE &c,BYTE a,BYTE b); // c = a-b
void sbc(BYTE &c,BYTE a,BYTE b); // c = a-b-cy
void mul(BYTE &h,BYTE &l,BYTE a,BYTE b); // (h,l) = a/b
void div(BYTE &h,BYTE &l,BYTE &r,BYTE ah,BYTE al,BYTE b); // (h,l) = (ah,al)/b ; r = (ah,al)%b
//---------------------------------------------------------------------------
void inc(BYTE &a) { if (a==0xFF) cy=1; else cy=0; a++; }
void dec(BYTE &a) { if (a==0x00) cy=1; else cy=0; a--; }
void add(BYTE &c,BYTE a,BYTE b)
{
c=a+b;
cy=BYTE(((a &1)+(b &1) )>>1);
cy=BYTE(((a>>1)+(b>>1)+cy)>>7);
}
void adc(BYTE &c,BYTE a,BYTE b)
{
c=a+b+cy;
cy=BYTE(((a &1)+(b &1)+cy)>>1);
cy=BYTE(((a>>1)+(b>>1)+cy)>>7);
}
void sub(BYTE &c,BYTE a,BYTE b)
{
c=a-b;
if (a<b) cy=1; else cy=0;
}
void sbc(BYTE &c,BYTE a,BYTE b)
{
c=a-b-cy;
if (cy) { if (a<=b) cy=1; else cy=0; }
else { if (a< b) cy=1; else cy=0; }
}
void mul(BYTE &h,BYTE &l,BYTE a,BYTE b)
{
BYTE ah,al;
h=0; l=0; ah=0; al=a;
if ((a==0)||(b==0)) return;
// long binary multiplication
for (;b;b>>=1)
{
if (BYTE(b&1))
{
add(l,l,al); // (h,l)+=(ah,al)
adc(h,h,ah);
}
add(al,al,al); // (ah,al)<<=1
adc(ah,ah,ah);
}
}
void div(BYTE &d1,BYTE &d0,BYTE &r,BYTE a1,BYTE a0,BYTE z0)
{
// D = (a0/z0) + ((a1*256)/z0) + (( (a0%z0) + ((a1*256)%z0) )/z0);
// D = (a0/z0) + ((a1/z0)*256) + ((a1%z0)*(256/z0)) + (( (a0%z0) + ((a1%z0)*(256%z0)) )/z0);
// edge cases
if (z0==0){ d0= 0; d1= 0; r=0; }
if (z0==1){ d0=a0; d1=a1; r=0; }
// normal division
if (z0>=2)
{
BYTE i0,i1,e0,e1,f0,f1,t,dt;
i0=0xFF/z0; if ((z0&(z0-1))==0) i0++; // i0 = 256/z0
i1=i0*z0; i1^=0xFF; i1++; // i1 = 256%z0
t=a1%z0;
mul(e1,e0,t,i0); // e = (a1%z0)*(256/z0)
mul(f1,f0,t,i1); // f = (a1%z0)*(256%z0)
add(f0,f0,a0%z0); // f = (a0%z0) + (a1%z0)*(256%z0)
adc(f1,f1,0);
add(d0,a0/z0,e0);
adc(d1,a1/z0,e1);
// t = division of problematic term by z0
t=0;
for (;f1;)
{
dt=f1*i0;
mul(e1,e0,dt,z0);
sub(f0,f0,e0);
sbc(f1,f1,e1);
t+=dt;
}
if (f0>=z0) t+=f0/z0;
// correct output
add(d0,d0,t);
adc(d1,d1,0);
// remainder
r=d0*z0;
r=a0-r;
}
}
//---------------------------------------------------------------------------
The 8bit ALU is not optimized at all I just busted it to test it right now as original project is nowhere to found... I assume you are doing it in asm so you use can use CPU/ALU instructions carry instead. The only important function is the div.
Notes:
This is only 8 bit. To convert it to 64 bit just change all 0xFF to 0xFFFFFFFFFFFFFFFF and BYTE to your data type and <<8 to <<64.
Division result is in d0, d1 and remainder is in r
Code does not handle negative values.
Sadly the term:
(( (a0%z0) + ((a1%z0)*(256%z0)) )/z0);
in its current state requires also 16 bit division (not full though as result is not arbitrary instead a composite of two mod z0 values). I managed to avoid long division by few (for 16bit:8bit is the worst case 7) iterations. However my guts are telling me it should be computed simpler using some modular math identity I do not know or cant think of right now. This makes this division relatively slow.
How do you sort an array of strings naturally in different programming languages? Post your implementation and what language it is in in the answer.
Here's how you can get explorer-like behaviour in Python:
#!/usr/bin/env python
"""
>>> items = u'a1 a003 b2 a2 a10 1 10 20 2 c100'.split()
>>> items.sort(explorer_cmp)
>>> for s in items:
... print s,
1 2 10 20 a1 a2 a003 a10 b2 c100
>>> items.sort(key=natural_key, reverse=True)
>>> for s in items:
... print s,
c100 b2 a10 a003 a2 a1 20 10 2 1
"""
import re
def natural_key(astr):
"""See http://www.codinghorror.com/blog/archives/001018.html"""
return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', astr)]
def natural_cmp(a, b):
return cmp(natural_key(a), natural_key(b))
try: # use explorer's comparison function if available
import ctypes
explorer_cmp = ctypes.windll.shlwapi.StrCmpLogicalW
except (ImportError, AttributeError):
# not on Windows or old python version
explorer_cmp = natural_cmp
if __name__ == '__main__':
import doctest; doctest.testmod()
To support Unicode strings, .isdecimal() should be used instead of .isdigit().
.isdigit() may also fail (return value that is not accepted by int()) for a bytestring on Python 2 in some locales e.g., '\xb2' ('²') in cp1252 locale on Windows.
JavaScript
Array.prototype.alphanumSort = function(caseInsensitive) {
for (var z = 0, t; t = this[z]; z++) {
this[z] = [], x = 0, y = -1, n = 0, i, j;
while (i = (j = t.charAt(x++)).charCodeAt(0)) {
var m = (i == 46 || (i >=48 && i <= 57));
if (m !== n) {
this[z][++y] = "";
n = m;
}
this[z][y] += j;
}
}
this.sort(function(a, b) {
for (var x = 0, aa, bb; (aa = a[x]) && (bb = b[x]); x++) {
if (caseInsensitive) {
aa = aa.toLowerCase();
bb = bb.toLowerCase();
}
if (aa !== bb) {
var c = Number(aa), d = Number(bb);
if (c == aa && d == bb) {
return c - d;
} else return (aa > bb) ? 1 : -1;
}
}
return a.length - b.length;
});
for (var z = 0; z < this.length; z++)
this[z] = this[z].join("");
}
Source
For MySQL, I personally use code from a Drupal module, which is available at hhttp://drupalcode.org/project/natsort.git/blob/refs/heads/5.x-1.x:/natsort.install.mysql
Basically, you execute the posted SQL script to create functions, and then use ORDER BY natsort_canon(field_name, 'natural')
Here's a readme about the function:
http://drupalcode.org/project/natsort.git/blob/refs/heads/5.x-1.x:/README.txt
Here's a cleanup of the code in the article the question linked to:
def sorted_nicely(strings):
"Sort strings the way humans are said to expect."
return sorted(strings, key=natural_sort_key)
def natural_sort_key(key):
import re
return [int(t) if t.isdigit() else t for t in re.split(r'(\d+)', key)]
But actually I haven't had occasion to sort anything this way.
If the OP is asking about idomatic sorting expressions, then not all languages have a natural expression built in. For c I'd go to <stdlib.h> and use qsort. Something on the lines of :
/* non-functional mess deleted */
to sort the arguments into lexical order. Unfortunately this idiom is rather hard to parse for those not used the ways of c.
Suitably chastened by the downvote, I actually read the linked article. Mea culpa.
In anycase the original code did not work, except in the single case I tested. Damn. Plain vanilla c does not have this function, nor is it in any of the usual libraries.
The code below sorts the command line arguments in the natural way as linked. Caveat emptor as it is only lightly tested.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int naturalstrcmp(const char **s1, const char **s2);
int main(int argc, char **argv){
/* Sort the command line arguments in place */
qsort(&argv[1],argc-1,sizeof(char*),
(int(*)(const void *, const void *))naturalstrcmp);
while(--argc){
printf("%s\n",(++argv)[0]);
};
}
int naturalstrcmp(const char **s1p, const char **s2p){
if ((NULL == s1p) || (NULL == *s1p)) {
if ((NULL == s2p) || (NULL == *s2p)) return 0;
return 1;
};
if ((NULL == s2p) || (NULL == *s2p)) return -1;
const char *s1=*s1p;
const char *s2=*s2p;
do {
if (isdigit(s1[0]) && isdigit(s2[0])){
/* Compare numbers as numbers */
int c1 = strspn(s1,"0123456789"); /* Could be more efficient here... */
int c2 = strspn(s2,"0123456789");
if (c1 > c2) {
return 1;
} else if (c1 < c2) {
return -1;
};
/* the digit strings have equal length, so compare digit by digit */
while (c1--) {
if (s1[0] > s2[0]){
return 1;
} else if (s1[0] < s2[0]){
return -1;
};
s1++;
s2++;
};
} else if (s1[0] > s2[0]){
return 1;
} else if (s1[0] < s2[0]){
return -1;
};
s1++;
s2++;
} while ( (s1!='\0') || (s2!='\0') );
return 0;
}
This approach is pretty brute force, but it is simple and can probably be duplicated in any imperative language.
I just use StrCmpLogicalW. It does exactly what Jeff is wanting, since it's the same API that explorer uses. Admittedly, it's not portable.
In C++:
bool NaturalLess(const wstring &lhs, const wstring &rhs)
{
return StrCmpLogicalW(lhs.c_str(), rhs.c_str()) < 0;
}
vector<wstring> strings;
// ... load the strings
sort(strings.begin(), strings.end(), &NaturalLess);
Just a link to some nice work in Common Lisp by Eric Normand:
http://www.lispcast.com/wordpress/2007/12/human-order-sorting/
In C, this solution correctly handles numbers with leading zeroes:
#include <stdlib.h>
#include <ctype.h>
/* like strcmp but compare sequences of digits numerically */
int strcmpbynum(const char *s1, const char *s2) {
for (;;) {
if (*s2 == '\0')
return *s1 != '\0';
else if (*s1 == '\0')
return 1;
else if (!(isdigit(*s1) && isdigit(*s2))) {
if (*s1 != *s2)
return (int)*s1 - (int)*s2;
else
(++s1, ++s2);
} else {
char *lim1, *lim2;
unsigned long n1 = strtoul(s1, &lim1, 10);
unsigned long n2 = strtoul(s2, &lim2, 10);
if (n1 > n2)
return 1;
else if (n1 < n2)
return -1;
s1 = lim1;
s2 = lim2;
}
}
}
If you want to use it with qsort, use this auxiliary function:
static int compare(const void *p1, const void *p2) {
const char * const *ps1 = p1;
const char * const *ps2 = p2;
return strcmpbynum(*ps1, *ps2);
}
And you can do something on the order of
char *lines = ...;
qsort(lines, next, sizeof(lines[0]), compare);
In C++ I use this example code to do natural sorting. The code requires the boost library.
Note that for most such questions, you can just consult the Rosetta Code Wiki. I adapted my answer from the entry for sorting integers.
In a system's programming language doing something like this is generally going to be uglier than with a specialzed string-handling language. Fortunately for Ada, the most recent version has a library routine for just this kind of task.
For Ada 2005 I believe you could do something along the following lines (warning, not compiled!):
type String_Array is array(Natural range <>) of Ada.Strings.Unbounded.Unbounded_String;
function "<" (L, R : Ada.Strings.Unbounded.Unbounded_String) return boolean is
begin
--// Natural ordering predicate here. Sorry to cheat in this part, but
--// I don't exactly grok the requirement for "natural" ordering. Fill in
--// your proper code here.
end "<";
procedure Sort is new Ada.Containers.Generic_Array_Sort
(Index_Type => Natural;
Element_Type => Ada.Strings.Unbounded.Unbounded_String,
Array_Type => String_Array
);
Example use:
using Ada.Strings.Unbounded;
Example : String_Array := (To_Unbounded_String ("Joe"),
To_Unbounded_String ("Jim"),
To_Unbounded_String ("Jane"),
To_Unbounded_String ("Fred"),
To_Unbounded_String ("Bertha"),
To_Unbounded_String ("Joesphus"),
To_Unbounded_String ("Jonesey"));
begin
Sort (Example);
...
end;
Python, using itertools:
def natural_key(s):
return tuple(
int(''.join(chars)) if isdigit else ''.join(chars)
for isdigit, chars in itertools.groupby(s, str.isdigit)
)
Result:
>>> natural_key('abc-123foo456.xyz')
('abc-', 123, 'foo', 456, '.xyz')
Sorting:
>>> sorted(['1.1.1', '1.10.4', '1.5.0', '42.1.0', '9', 'banana'], key=natural_key)
['1.1.1', '1.5.0', '1.10.4', '9', '42.1.0', 'banana']
My implementation on Clojure 1.1:
(ns alphanumeric-sort
(:import [java.util.regex Pattern]))
(defn comp-alpha-numerical
"Compare two strings alphanumerically."
[a b]
(let [regex (Pattern/compile "[\\d]+|[a-zA-Z]+")
sa (re-seq regex a)
sb (re-seq regex b)]
(loop [seqa sa seqb sb]
(let [counta (count seqa)
countb (count seqb)]
(if-not (not-any? zero? [counta countb]) (- counta countb)
(let [c (first seqa)
d (first seqb)
c1 (read-string c)
d1 (read-string d)]
(if (every? integer? [c1 d1])
(def result (compare c1 d1)) (def result (compare c d)))
(if-not (= 0 result) result (recur (rest seqa) (rest seqb)))))))))
(sort comp-alpha-numerical ["a1" "a003" "b2" "a10" "a2" "1" "10" "20" "2" "c100"])
Result:
("1" "2" "10" "20" "a1" "a2" "a003" "a10" "b2" "c100")
For Tcl, the -dict (dictionary) option to lsort:
% lsort -dict {a b 1 c 2 d 13}
1 2 13 a b c d
php has a easy function "natsort" to do that,and I implements it by myself:
<?php
$temp_files = array('+====','-==',"temp15-txt","temp10.txt",
"temp1.txt","tempe22.txt","temp2.txt");
$my_arr = $temp_files;
natsort($temp_files);
echo "Natural order: ";
print_r($temp_files);
echo "My Natural order: ";
usort($my_arr,'my_nat_func');
print_r($my_arr);
function is_alpha($a){
return $a>='0'&&$a<='9' ;
}
function my_nat_func($a,$b){
if(preg_match('/[0-9]/',$a)){
if(preg_match('/[0-9]/',$b)){
$i=0;
while(!is_alpha($a[$i])) ++$i;
$m = intval(substr($a,$i));
$i=0;
while(!is_alpha($b[$i])) ++$i;
$n = intval(substr($b,$i));
return $m>$n?1:($m==$n?0:-1);
}
return 1;
}else{
if(preg_match('/[0-9]/',$b)){
return -1;
}
return $a>$b?1:($a==$b?0:-1);
}
}
Java solution:-
This can be achieved by implementing new Comparator<String> and pass it to Collections.sort(list, comparator) method.
#Override
public int compare(String s1, String s2) {
int len1 = s1.length();
int len2 = s2.length();
int lim = Math.min(len1, len2);
char v1[] = s1.toCharArray();
char v2[] = s2.toCharArray();
int k = 0;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
if(this.isInteger(c1) && this.isInteger(c2)) {
int i1 = grabContinousInteger(v1, k);
int i2 = grabContinousInteger(v2, k);
return i1 - i2;
}
return c1 - c2;
}
k++;
}
return len1 - len2;
}
private boolean isInteger(char c) {
return c >= 48 && c <= 57; // ascii value 0-9
}
private int grabContinousInteger(char[] arr, int k) {
int i = k;
while(i < arr.length && this.isInteger(arr[i])) {
i++;
}
return Integer.parseInt(new String(arr, k, i - k));
}