Forth и другие саморасширяющиеся системы программирования Locations of visitors to this page
Текущее время: Вт мар 19, 2024 15:19

...
Google Search
Forth-FAQ Spy Grafic

Часовой пояс: UTC + 3 часа [ Летнее время ]




Начать новую тему Ответить на тему  [ Сообщений: 32 ]  На страницу 1, 2, 3  След.
Автор Сообщение
 Заголовок сообщения: FALSE раньше и теперь
СообщениеДобавлено: Пт апр 18, 2014 09:57 
Не в сети

Зарегистрирован: Вт ноя 06, 2012 10:41
Сообщения: 23
Благодарил (а): 4 раз.
Поблагодарили: 1 раз.
Добрый день. Какое-то время назад я прочитал пару книг о Форте (Броуди, если не ошибаюсь) и ещё что-то, в общем оттуда (откуда именно я не помню, а может и вообще это ошибка) мне запомнилось что значение логического "нет" в численном виде представляется в форте как "-1", а не "0", как принято в других языках.
Просматривая последние стандарты Форта я такого не обнаружил. Подскажите, я вообще неправильно запомнил, или это поведение менялось со временем? Если верно второе, то почему?


Вернуться к началу
 Профиль Отправить личное сообщение  
Ответить с цитатой  
 Заголовок сообщения: Re: FALSE раньше и теперь
СообщениеДобавлено: Пт апр 18, 2014 10:09 
Renha писал(а):
Подскажите, я вообще неправильно запомнил, или это поведение менялось со временем?
Неправильно запомнили. FALSE всегда и везде было 0.
TRUE в первых работах Мура встречалось и "1". "-1" было сделано из соображений упрощения перехода от арифметики к логике. При этом IF обязан считать истинным любое ненулевое значение.


Вернуться к началу
  
Ответить с цитатой  
 Заголовок сообщения: Re: FALSE раньше и теперь
СообщениеДобавлено: Пт апр 18, 2014 10:30 
Не в сети

Зарегистрирован: Вт ноя 06, 2012 10:41
Сообщения: 23
Благодарил (а): 4 раз.
Поблагодарили: 1 раз.
gudleifr писал(а):
Renha писал(а):
Подскажите, я вообще неправильно запомнил, или это поведение менялось со временем?
Неправильно запомнили. FALSE всегда и везде было 0.
TRUE в первых работах Мура встречалось и "1". "-1" было сделано из соображений упрощения перехода от арифметики к логике. При этом IF обязан считать истинным любое ненулевое значение.

спасибо


Вернуться к началу
 Профиль Отправить личное сообщение  
Ответить с цитатой  
 Заголовок сообщения: Re: FALSE раньше и теперь
СообщениеДобавлено: Пт апр 18, 2014 19:33 
Не в сети

Зарегистрирован: Ср май 10, 2006 13:51
Сообщения: 202
Благодарил (а): 3 раз.
Поблагодарили: 4 раз.
ANSI-94:

Цитата:
3.1.3.1 Флаги

Флаги могут иметь одно из двух логических значений: true или false. Программы, которые используют флаги как арифметические операнды, имеют зависимость от окружения.

True флаг, возвращенный стандартным словом должен иметь значение одна-ячейка со всеми установленными битами. A false флаг, возвращенный стандартным словом должен иметь значение одна-ячейка со всеми сброшенными битами.



За это сообщение автора oco поблагодарил: Renha
Вернуться к началу
 Профиль Отправить личное сообщение  
Ответить с цитатой  
 Заголовок сообщения: Re: FALSE раньше и теперь
СообщениеДобавлено: Пт апр 18, 2014 20:49 
Не в сети

Зарегистрирован: Чт ноя 23, 2006 00:44
Сообщения: 494
Откуда: СПб
Благодарил (а): 19 раз.
Поблагодарили: 8 раз.
gudleifr писал(а):
Renha писал(а):
Подскажите, я вообще неправильно запомнил, или это поведение менялось со временем?
Неправильно запомнили. FALSE всегда и везде было 0.
TRUE в первых работах Мура встречалось и "1". "-1" было сделано из соображений упрощения перехода от арифметики к логике. При этом IF обязан считать истинным любое ненулевое значение.

Вот по этому поводу у меня было приключение!
Много лет тому взад, я трудился инженером-программистом в конторе использующей SCADA InTouch (Wonderware).
Всё описанное выполнялось на SPF/
Как "всем" известно :)) , общаться с InTouch можно (на тот момент времени) было либо через OPC (OLE for Process Controll) или через DDE. Решил я написать GUI "сервер" для отладки. Короче! Не осилил я тогда OPC, а вот с DDE всё получилось, но долго не мог начать общение с клиентом и вроде все делаю правильно (по MSDN), но результат 0-вой. Ситуация: Сервер посылает TRUE, а клиент должен ответить. Я честно посылаю Фортовское TRUE=-1, а в ответ ошибка. :!: Благо у меня оказалась книжка по "православному" Си и благо что там обозначили значение "правослваного" сишного TRUE=1. Поправил код и всё заработало!



За это сообщение автора Ilya поблагодарил: Renha
Вернуться к началу
 Профиль Отправить личное сообщение  
Ответить с цитатой  
 Заголовок сообщения: Re: FALSE раньше и теперь
СообщениеДобавлено: Пт апр 18, 2014 21:24 
Не в сети

Зарегистрирован: Вт ноя 06, 2012 10:41
Сообщения: 23
Благодарил (а): 4 раз.
Поблагодарили: 1 раз.
oco писал(а):
ANSI-94:

Цитата:
3.1.3.1 Флаги

Флаги могут иметь одно из двух логических значений: true или false. Программы, которые используют флаги как арифметические операнды, имеют зависимость от окружения.

True флаг, возвращенный стандартным словом должен иметь значение одна-ячейка со всеми установленными битами. A false флаг, возвращенный стандартным словом должен иметь значение одна-ячейка со всеми сброшенными битами.

Видимо я отсюда и перепутал всё..


Вернуться к началу
 Профиль Отправить личное сообщение  
Ответить с цитатой  
 Заголовок сообщения: Re: FALSE раньше и теперь
СообщениеДобавлено: Ср апр 13, 2016 19:46 
Не в сети
Аватара пользователя

Зарегистрирован: Ср фев 23, 2011 20:42
Сообщения: 600
Откуда: Карелия
Благодарил (а): 3 раз.
Поблагодарили: 24 раз.
gudleifr писал(а):
TRUE в первых работах Мура встречалось и "1".
Если точнее, то TRUE=-1 стало начиная с Forth-83, а до этого (FIG-Forth, Forth-79) было 1.

Из стандарта Forth-79:
Standard word definitions leave 1 for true, 0 for false.
Из стандарта Forth-83:
all standard words return a 16-bit value with all bits set to one when returning a 'true' flag.


Вернуться к началу
 Профиль Отправить личное сообщение  
Ответить с цитатой  
 Заголовок сообщения: Re: FALSE раньше и теперь
СообщениеДобавлено: Пн дек 19, 2016 09:59 
Не в сети

Зарегистрирован: Сб дек 17, 2016 23:03
Сообщения: 60
Благодарил (а): 0 раз.
Поблагодарили: 0 раз.
Ethereal писал(а):
gudleifr писал(а):
TRUE в первых работах Мура встречалось и "1".
Если точнее, то TRUE=-1 стало начиная с Forth-83, а до этого (FIG-Forth, Forth-79) было 1.

Из стандарта Forth-79:
Standard word definitions leave 1 for true, 0 for false.
Из стандарта Forth-83:
all standard words return a 16-bit value with all bits set to one when returning a 'true' flag.


In Straight Forth TRUE will be 1 and FALSE will be 0.

A flag can be added to a counter --- I believe that this is more common than using a flag as a mask for logical functions --- if you want a mask though, then just NEGATE the flag.

I'm flexible on the Straight Forth design though --- if people demand that TRUE be -1 and say that they will leave if it is 1, then I will go with -1 --- I don't care very much about the question.


Вернуться к началу
 Профиль Отправить личное сообщение  
Ответить с цитатой  
 Заголовок сообщения: Re: FALSE раньше и теперь
СообщениеДобавлено: Вт дек 20, 2016 02:06 
Не в сети
Administrator
Administrator
Аватара пользователя

Зарегистрирован: Вт май 02, 2006 22:48
Сообщения: 7958
Благодарил (а): 25 раз.
Поблагодарили: 144 раз.
This is a very intresting question. There are arguments for both 1 and -1 and because everyone should know 'Forth is very flexiblr language' why don;t allow programmers to thinks freely about this? Indeed, I don't think any of these values must be used 'because of Forth spirit' or because some Forth-guru use certain value. Let's think and try.

Btw... what about having TRUE variable?


Вернуться к началу
 Профиль Отправить личное сообщение  
Ответить с цитатой  
 Заголовок сообщения: Re: FALSE раньше и теперь
СообщениеДобавлено: Вт дек 20, 2016 06:00 
Не в сети

Зарегистрирован: Сб дек 17, 2016 23:03
Сообщения: 60
Благодарил (а): 0 раз.
Поблагодарили: 0 раз.
Hishnik писал(а):
This is a very intresting question. There are arguments for both 1 and -1 and because everyone should know 'Forth is very flexiblr language' why don;t allow programmers to thinks freely about this? Indeed, I don't think any of these values must be used 'because of Forth spirit' or because some Forth-guru use certain value. Let's think and try.

Btw... what about having TRUE variable?

This kind of thinking is the slippery slope where ANS-Forth slid into failure.

The major problem with ANS-Forth is ambiguity. The ANS-document contains phrases such as: "may or may not," "implementation defined" and "ambiguous." A lot of political concessions were made. For example, some Forth compiler-writers knew that it was a good idea for the control-flow stack and the data-stack to be separate. This is because meta-compiling words need to hold data on the data-stack, but allowing control-flow words such as IF BEGIN etc. to put their data on the data-stack is a problem because this control-flow data is on top of the user's data preventing the user from accessing his own data. Forth Inc. however uses the data-stack for control-flow data because this is more "convenient" for the compiler-writer. The solution in ANS-Forth was to say that the control-flow stack may or may not be the same as the data-stack. This is not a solution however, because the two methods (same stack or separate stacks) are not compatible. Programs that depend upon having separate stacks will not compile and run correctly on compilers (SwiftForth) that have the control-flow stack and the data-stack being the same. As a practical matter, programmers have to assume the worst-case scenario (SwiftForth) if they want their programs to be considered to be ANS-Forth compliant because any program that fails to compile and run correctly on SwiftForth will be judged to be non-compliant by Elizabeth Rather.

ANS-Forth is a Standard that doesn't standardize anything. ANS-Forth is full of ambiguity and complication. Ultimately, being "ANS-Forth compliant" just means that Elizabeth Rather says that you are ANS-Forth compliant --- this does not mean that your program will compile and run correctly on every ANS-Forth compiler --- most ANS-Forth compliant programs only compile and run correctly on one particular ANS-Forth compiler (the same situation as if we didn't have a Standard at all).

It is a bad idea to let the compiler-writer decide if TRUE is 1 or -1 because programs won't port unmodified between compilers. It is also a bad idea to make TRUE a variable that the programmer can set, because code will be written to assume either 1 or -1 --- the code won't run correctly when TRUE is set to the wrong value.

It is a good idea to decide if TRUE is 1 or -1 and stick with that plan. It is better to make a bad decision than to make no decision. If TRUE is defined as 1 then we have made a decision. If a lot of programmers need TRUE to be -1 then they will need to put a NEGATE in their program prior to using a flag as a mask. This is a minor cost. We have made a bad decision, but this makes no practical difference. Writing a Forth Standard involves making decisions --- so, make a decision for 1 or -1 and stand on your decision --- don't avoid making a decision by deciding that TRUE can be either 1 or -1 because avoiding a decision is much worse than making a bad decision.

Elizabeth Rather avoided making decisions in ANS-Forth because her goal was to get as many Forth programmers as possible to support the ANS-Forth Standard so she could claim that she had the support of the entire Forth community. When a conflict arose, in which some Forth programmers wanted one decision and other Forth programmers wanted another contradictory decision, she said: "Both of you are ANS-Forth compliant! This will be implementation defined! Any implementation will be ANS-Forth compliant!" The result is that ANS-Forth is full of ambiguity and programs can't be ported from one ANS-Forth compliant compiler to another ANS-Forth compliant compiler because the program assumes one implementation or another.

Elizabeth Rather is like a kindergarten teacher who tells the children: "All of you can be winners!" This is not reality however. Some will win and some will lose. If you want TRUE to be -1 and Straight Forth defines TRUE as 1 then you will lose --- you will have to pay the penalty (you will have to use NEGATE to convert your flag into 0/-1 which can be used as a mask) --- this is a minor penalty though, so you will survive. 8)


Вернуться к началу
 Профиль Отправить личное сообщение  
Ответить с цитатой  
 Заголовок сообщения: Re: FALSE раньше и теперь
СообщениеДобавлено: Вт дек 20, 2016 14:48 
Не в сети
Administrator
Administrator
Аватара пользователя

Зарегистрирован: Вт май 02, 2006 22:48
Сообщения: 7958
Благодарил (а): 25 раз.
Поблагодарили: 144 раз.
I think conversations may start only after collecting real project requirements. This is an empty discussion about where to place control-flow data, unless we already have a set of tests and sample programs. Particulary, I use separate stacks because already faced situations where it is required.

HughAguilar писал(а):
ANS-Forth is a Standard that doesn't standardize anything. ANS-Forth is full of ambiguity and complication. Ultimately, being "ANS-Forth compliant" just means that Elizabeth Rather says that you are ANS-Forth compliant --- this does not mean that your program will compile and run correctly on every ANS-Forth compiler --- most ANS-Forth compliant programs only compile and run correctly on one particular ANS-Forth compiler (the same situation as if we didn't have a Standard at all).


This is a well-known (even here) dream about Perfect Standard, which will be used to collecting all forthers together :) How this will work after standard will be accepted? Nobody knows. How projects will appear? Who will pay for projects? Nobody knows, but many forthers hopes this will start right after most of them will accept a Perfect Standard.

HughAguilar писал(а):
It is a bad idea to let the compiler-writer decide if TRUE is 1 or -1 because programs won't port unmodified between compilers. It is also a bad idea to make TRUE a variable that the programmer can set, because code will be written to assume either 1 or -1 --- the code won't run correctly when TRUE is set to the wrong value.


You can check this at the start and set the value you need. When we write something like 2 2 = IF we don't need to know how TRUE and FASLE are represented, while IF can handle them properly. Problems are appear when we try to convert values from boolean to integer and back. If we want to make some arithmetic with boolean representation, we really need to be sure what exactly value used for TRUE.

Having TRUE = 1 may be useful for several tricks with 'boolean as integer' when we want to skip to next memory cell. It has known disadvantage when 4 TRUE AND will return FALSE because literal does not contain 1 in LSB.

We can choose either 1 or -1 or make explicit boolean-to-integer conversion mandatory (i.e. L>S will convert existing logical value to known integer, and S>L will convert non-zero values to TRUE, as described in standard).

HughAguilar писал(а):
It is better to make a bad decision than to make no decision.

And it is better to have several Forth-based dialects than trying to find a silver bullet. Let's start with any kind of document and see what happens.


Вернуться к началу
 Профиль Отправить личное сообщение  
Ответить с цитатой  
 Заголовок сообщения: Re: FALSE раньше и теперь
СообщениеДобавлено: Ср дек 21, 2016 10:57 
Не в сети

Зарегистрирован: Сб дек 17, 2016 23:03
Сообщения: 60
Благодарил (а): 0 раз.
Поблагодарили: 0 раз.
Hishnik писал(а):
HughAguilar писал(а):
ANS-Forth is a Standard that doesn't standardize anything. ANS-Forth is full of ambiguity and complication. Ultimately, being "ANS-Forth compliant" just means that Elizabeth Rather says that you are ANS-Forth compliant --- this does not mean that your program will compile and run correctly on every ANS-Forth compiler --- most ANS-Forth compliant programs only compile and run correctly on one particular ANS-Forth compiler (the same situation as if we didn't have a Standard at all).

This is a well-known (even here) dream about Perfect Standard, which will be used to collecting all forthers together :) How this will work after standard will be accepted? Nobody knows. How projects will appear? Who will pay for projects? Nobody knows, but many forthers hopes this will start right after most of them will accept a Perfect Standard.

This is true of all languages.
Lua has become popular, mostly because it was used in "World of WarCraft," and then it took off from there.
Ruby has become popular, mostly because it was used in "Rails," and then it took off from there.

All languages start out as VCIW (voices crying in the wilderness) --- some VCIW get heard --- some languish unheard and die out.

Hishnik писал(а):
HughAguilar писал(а):
It is a bad idea to let the compiler-writer decide if TRUE is 1 or -1 because programs won't port unmodified between compilers. It is also a bad idea to make TRUE a variable that the programmer can set, because code will be written to assume either 1 or -1 --- the code won't run correctly when TRUE is set to the wrong value.


You can check this at the start and set the value you need. When we write something like 2 2 = IF we don't need to know how TRUE and FASLE are represented, while IF can handle them properly. Problems are appear when we try to convert values from boolean to integer and back. If we want to make some arithmetic with boolean representation, we really need to be sure what exactly value used for TRUE.

Having TRUE = 1 may be useful for several tricks with 'boolean as integer' when we want to skip to next memory cell. It has known disadvantage when 4 TRUE AND will return FALSE because literal does not contain 1 in LSB.

We can choose either 1 or -1 or make explicit boolean-to-integer conversion mandatory (i.e. L>S will convert existing logical value to known integer, and S>L will convert non-zero values to TRUE, as described in standard).

All of this is obvious. If 1/2 of the Forthers want TRUE to be 1 and 1/2 want TRUE to be -1 then whichever way I choose 1/2 will have to use NEGATE on their flag and will damn me to Hell for it --- I can't make everybody happy.

Hishnik писал(а):
HughAguilar писал(а):
It is better to make a bad decision than to make no decision.

And it is better to have several Forth-based dialects than trying to find a silver bullet. Let's start with any kind of document and see what happens.

I'm not actually opposed to having several Forth dialects. I think that both Oforth and Factor are good languages in their own way. It is not my goal to steal all of their users and then stomp their withered corpses into the dirt.

Straight Forth is different from Oforth and Factor (because I don't have tagged data and GC) and it would be used for different purposes --- some programmers may use Straight Forth for some projects and Oforth or Factor for other projects.

I had previously been writing Straight Forth to define a "number" as a 64-bit fixed-point with an assumed unity of 2^32.

I am now thinking that this doesn't give the user anything that the user can't already get using IEEE-754 in any other language (C, etc.). A better plan may be to define a "number" as a pair of 64-bit integers which are the numerator and denominator. This would be slower, but it would give the user a feature that he can't get in any other language --- this would make Straight Forth distinctive --- users who need the precision of ratios would have a reason to use Straight Forth rather than C or any other language.

It is important to find a niche --- otherwise I would be: "a Jack of all trades and a master of none" (you may have to translate this proverb into Russian as I doubt that Google Translate will give your Russian-speaking friends words that make sense).


Вернуться к началу
 Профиль Отправить личное сообщение  
Ответить с цитатой  
 Заголовок сообщения: Re: FALSE раньше и теперь
СообщениеДобавлено: Чт дек 22, 2016 04:11 
Не в сети
Administrator
Administrator
Аватара пользователя

Зарегистрирован: Вт май 02, 2006 22:48
Сообщения: 7958
Благодарил (а): 25 раз.
Поблагодарили: 144 раз.
HughAguilar писал(а):
This is true of all languages.
Lua has become popular, mostly because it was used in "World of WarCraft," and then it took off from there.
Ruby has become popular, mostly because it was used in "Rails," and then it took off from there.

This is also true for SP-Forth. There is Eserv written by SPF author and nnCron by other programmer which made SPF popular enough. This does not discard SPF features (unfortunately, they are no longer actual).

More important is a fact we may not rely on popularity in the future. Since Forth looks like a kind of application in the terms of complexity, we can just write another dialect for our target domain and don't think how programmers will follow us.

HughAguilar писал(а):
All of this is obvious. If 1/2 of the Forthers want TRUE to be 1 and 1/2 want TRUE to be -1 then whichever way I choose 1/2 will have to use NEGATE on their flag and will damn me to Hell for it --- I can't make everybody happy.

Of course. You can just declare you want to have TRUE = 1 and invite others to take part... or to write their own Forths.

HughAguilar писал(а):
I am now thinking that this doesn't give the user anything that the user can't already get using IEEE-754 in any other language (C, etc.). A better plan may be to define a "number" as a pair of 64-bit integers which are the numerator and denominator. This would be slower, but it would give the user a feature that he can't get in any other language --- this would make Straight Forth distinctive --- users who need the precision of ratios would have a reason to use Straight Forth rather than C or any other language.


Supporting data formats is an important question. I'm sure common data formats should be supported. Having too uncommon representation as a mandatory is not good. Support additional useful format for the certain niche is a serious feature. My main reason to leave SP-Forth was a fact there was no floating point numbers support and no way to add it without changing source code (what about new versions in this case?). So numerator/denominator as an option / additional library looks fine as a feature, but not as only existing number format.

HughAguilar писал(а):
It is important to find a niche --- otherwise I would be: "a Jack of all trades and a master of none"

This is understandable :)


Вернуться к началу
 Профиль Отправить личное сообщение  
Ответить с цитатой  
 Заголовок сообщения: Re: FALSE раньше и теперь
СообщениеДобавлено: Чт дек 22, 2016 13:02 
Цитата:
1 or -1 ???

Use the source, Luke, use the source!

Value other than zero!

If you can select suitable value for a constant, don't use it! And, generally, don't use a constants!
---
Цитата:
32-bit, 64-bit, IEEE, 64*2...

You confuse FORTH machine and the "problem-oriented machine of data handling" written on it.


Вернуться к началу
  
Ответить с цитатой  
 Заголовок сообщения: Re: FALSE раньше и теперь
СообщениеДобавлено: Пт дек 23, 2016 00:33 
Не в сети

Зарегистрирован: Сб дек 17, 2016 23:03
Сообщения: 60
Благодарил (а): 0 раз.
Поблагодарили: 0 раз.
Hishnik писал(а):
Supporting data formats is an important question. I'm sure common data formats should be supported. Having too uncommon representation as a mandatory is not good. Support additional useful format for the certain niche is a serious feature. My main reason to leave SP-Forth was a fact there was no floating point numbers support and no way to add it without changing source code (what about new versions in this case?). So numerator/denominator as an option / additional library looks fine as a feature, but not as only existing number format.

HughAguilar писал(а):
It is important to find a niche --- otherwise I would be: "a Jack of all trades and a master of none"

This is understandable :)

Well, I'm thinking now that I will make the numerator/denominator format the standard which + - * / etc. work on. This provides a lot better precision than IEEE-754 does, and high precision is the niche I think it is best to aim for.

Over on comp.lang.forth we have this thread:
https://groups.google.com/forum/#!topic ... 101-125%5D
Everybody is wondering about how to compare two floats for equality. Well, that is a problem with IEEE-754 --- theoretically equal floats may not be equal in the least significant digits --- you have to specify equality out to a certain precision. With numerator/denominator however, this shouldn't usually be a problem --- it might be a problem with transcendental functions such as SIN and LN etc. because these don't produce ratios --- it is certainly less of a problem though.

I could support IEEE-754 as an extension library. These would use F+ F- F* F/ etc.. I would advise everybody to ignore this extension library --- reduce the number of words that they need to learn --- only if absolutely necessary would they delve into this. I can make the float-stack only 8 elements in size --- this is the same as on the x87 --- the programmer can move floats from the float-stack to local variables as necessary to prevent the stack from overflowing.

I still don't think that most Forthers need the range of IEEE-754 floats. You mentioned in an email that this is needed in calculations involving quantum mechanics. Well, how many Forthers are studying that???


Вернуться к началу
 Профиль Отправить личное сообщение  
Ответить с цитатой  
Показать сообщения за:  Поле сортировки  
Начать новую тему Ответить на тему  [ Сообщений: 32 ]  На страницу 1, 2, 3  След.

Часовой пояс: UTC + 3 часа [ Летнее время ]


Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 1


Вы не можете начинать темы
Вы можете отвечать на сообщения
Вы не можете редактировать свои сообщения
Вы не можете удалять свои сообщения
Вы не можете добавлять вложения

Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
phpBB сборка от FladeX // Русская поддержка phpBB