Биохимия спиртового брожения: Основу технологии получения пива составляет спиртовое брожение, - при котором сахар превращается...
История развития хранилищ для нефти: Первые склады нефти появились в XVII веке. Они представляли собой землянные ямы-амбара глубиной 4…5 м...
Топ:
Эволюция кровеносной системы позвоночных животных: Биологическая эволюция – необратимый процесс исторического развития живой природы...
Комплексной системы оценки состояния охраны труда на производственном объекте (КСОТ-П): Цели и задачи Комплексной системы оценки состояния охраны труда и определению факторов рисков по охране труда...
Оценка эффективности инструментов коммуникационной политики: Внешние коммуникации - обмен информацией между организацией и её внешней средой...
Интересное:
Берегоукрепление оползневых склонов: На прибрежных склонах основной причиной развития оползневых процессов является подмыв водами рек естественных склонов...
Влияние предпринимательской среды на эффективное функционирование предприятия: Предпринимательская среда – это совокупность внешних и внутренних факторов, оказывающих влияние на функционирование фирмы...
Уполаживание и террасирование склонов: Если глубина оврага более 5 м необходимо устройство берм. Варианты использования оврагов для градостроительных целей...
Дисциплины:
2021-11-25 | 13 |
5.00
из
|
Заказать работу |
|
|
Повторное использование списков приносит двусмысленность. Если у нас есть:
LIST colours = red, green, blue, purple
LIST moods = mad, happy, blue
VAR status = blue
... как компилятор может узнать, какой синий цвет вы имели в виду?
We resolve these using a. syntax similar to that used for knots and stitches.
VAR status = colours.blue
...and the compiler will issue an error until you specify.
Note the "family name" of the state, and the variable containing a state, are totally separate. So
{ statesOfGrace == statesOfGrace.fallen:
// is the current state "fallen"
}
... is correct.
Advanced: a LIST is actually a variable
One surprising feature is the statement
LIST statesOfGrace = ambiguous, saintly, fallen
actually does two things simultaneously: it creates three values, ambiguous, saintly and fallen, and gives them the name-parent statesOfGrace if needed; and it creates a variable called statesOfGrace.
And that variable can be used like a normal variable. So the following is valid, if horribly confusing and a bad idea:
LIST statesOfGrace = ambiguous, saintly, fallen
~ statesOfGrace = 3.1415 // set the variable to a number not a list value
...and it wouldn't preclude the following from being fine:
~ temp anotherStateOfGrace = statesOfGrace.saintly
List Values
When a list is defined, the values are listed in an order, and that order is considered to be significant. In fact, we can treat these values as if they were numbers. (That is to say, they are enums.)
LIST volumeLevel = off, quiet, medium, loud, deafening
VAR lecturersVolume = quiet
VAR murmurersVolume = quiet
{ lecturersVolume < deafening:
~ lecturersVolume++
{ lecturersVolume > murmurersVolume:
~ murmurersVolume++
The murmuring gets louder.
}
}
The values themselves can be printed using the usual {...} syntax, but this will print their name.
The lecturer's voice becomes {lecturersVolume}.
Converting values to numbers
The numerical value, if needed, can be got explicitly using the LIST_VALUE function. Note the first value in a list has the value 1, and not the value 0.
The lecturer has {LIST_VALUE(deafening) - LIST_VALUE(lecturersVolume)} notches still available to him.
Converting numbers to values
You can go the other way by using the list's name as a function:
LIST Numbers = one, two, three
VAR score = one
~ score = Numbers(2) // score will be "two"
Advanced: defining your own numerical values
By default, the values in a list start at 1 and go up by one each time, but you can specify your own values if you need to.
LIST primeNumbers = two = 2, three = 3, five = 5
If you specify a value, but not the next value, ink will assume an increment of 1. So the following is the same:
|
LIST primeNumbers = two = 2, three, five = 5
Multivalued Lists
The following examples have all included one deliberate untruth, which we'll now remove. Lists - and variables containing list values - do not have to contain only one value.
Lists are boolean sets
A list variable is not a variable containing a number. Rather, a list is like the in/out nameboard in an accommodation block. It contains a list of names, each of which has a room-number associated with it, and a slider to say "in" or "out".
Maybe no one is in:
LIST DoctorsInSurgery = Adams, Bernard, Cartwright, Denver, Eamonn
Maybe everyone is:
LIST DoctorsInSurgery = (Adams), (Bernard), (Cartwright), (Denver), (Eamonn)
Or maybe some are and some aren't:
LIST DoctorsInSurgery = (Adams), Bernard, (Cartwright), Denver, Eamonn
Names in brackets are included in the initial state of the list.
Note that if you're defining your own values, you can place the brackets around the whole term or just the name:
LIST primeNumbers = (two = 2), (three) = 3, (five = 5)
Assiging multiple values
We can assign all the values of the list at once as follows:
~ DoctorsInSurgery = (Adams, Bernard)
~ DoctorsInSurgery = (Adams, Bernard, Eamonn)
We can assign the empty list to clear a list out:
~ DoctorsInSurgery = ()
Adding and removing entries
List entries can be added and removed, singly or collectively.
~ DoctorsInSurgery = DoctorsInSurgery + Adams ~ DoctorsInSurgery += Adams // this is the same as the above
~ DoctorsInSurgery -= Eamonn
~ DoctorsInSurgery += (Eamonn, Denver)
~ DoctorsInSurgery -= (Adams, Eamonn, Denver)
Trying to add an entry that's already in the list does nothing. Trying to remove an entry that's not there also does nothing. Neither produces an error, and a list can never contain duplicate entries.
Basic Queries
We have a few basic ways of getting information about what's in a list:
LIST DoctorsInSurgery = (Adams), Bernard, (Cartwright), Denver, Eamonn
{LIST_COUNT(DoctorsInSurgery)} // "2"
{LIST_MIN(DoctorsInSurgery)} // "Adams"
{LIST_MAX(DoctorsInSurgery)} // "Cartwright"
{LIST_RANDOM(DoctorsInSurgery)} // "Adams" or "Cartwright"
Testing for emptiness
Like most values in ink, a list can be tested "as it is", and will return true, unless it's empty.
{ DoctorsInSurgery: The surgery is open today. | Everyone has gone home. }
Testing for exact equality
Testing multi-valued lists is slightly more complex than single-valued ones. Equality (==) now means 'set equality' - that is, all entries are identical.
So one might say:
{ DoctorsInSurgery == (Adams, Bernard):
Dr Adams and Dr Bernard are having a loud argument in one corner.
}
If Dr Eamonn is in as well, the two won't argue, as the lists being compared won't be equal - DoctorsInSurgery will have an Eamonn that the list (Adams, Bernard) doesn't have.
Not equals works as expected:
{ DoctorsInSurgery!= (Adams, Bernard):
At least Adams and Bernard aren't arguing.
}
Testing for containment
What if we just want to simply ask if Adams and Bernard are present? For that we use a new operator, has, otherwise known as?.
{ DoctorsInSurgery? (Adams, Bernard):
Dr Adams and Dr Bernard are having a hushed argument in one corner.
|
}
And? can apply to single values too:
{ DoctorsInSurgery has Eamonn:
Dr Eamonn is polishing his glasses.
}
We can also negate it, with hasnt or!? (not?). Note this starts to get a little complicated as
DoctorsInSurgery!? (Adams, Bernard)
does not mean neither Adams nor Bernard is present, only that they are not both present (and arguing).
|
|
История создания датчика движения: Первый прибор для обнаружения движения был изобретен немецким физиком Генрихом Герцем...
Индивидуальные очистные сооружения: К классу индивидуальных очистных сооружений относят сооружения, пропускная способность которых...
Историки об Елизавете Петровне: Елизавета попала между двумя встречными культурными течениями, воспитывалась среди новых европейских веяний и преданий...
Папиллярные узоры пальцев рук - маркер спортивных способностей: дерматоглифические признаки формируются на 3-5 месяце беременности, не изменяются в течение жизни...
© cyberpedia.su 2017-2024 - Не является автором материалов. Исключительное право сохранено за автором текста.
Если вы не хотите, чтобы данный материал был у нас на сайте, перейдите по ссылке: Нарушение авторских прав. Мы поможем в написании вашей работы!