我想在字符串向量中找到最长的单词。使用 APL 我知道 shape 函数将返回字符串的长度,例如
⍴ 'string' ⍝ returns 6
reduce 函数允许我沿向量映射二元函数,但由于形状是一元的,这将不起作用。在这种情况下如何映射形状函数?例如:
如果向量定义为:
lst ← 'this is a string'
我想做这个:
⍴'this' ⍴'is' ⍴'a' ⍴'string'
我想在字符串向量中找到最长的单词。使用 APL 我知道 shape 函数将返回字符串的长度,例如
⍴ 'string' ⍝ returns 6
reduce 函数允许我沿向量映射二元函数,但由于形状是一元的,这将不起作用。在这种情况下如何映射形状函数?例如:
如果向量定义为:
lst ← 'this is a string'
我想做这个:
⍴'this' ⍴'is' ⍴'a' ⍴'string'
“典型”方法是将其视为分段(或:分隔)字符串并在其前面加上分隔符(空白)并将其传递给 dfn 以进行进一步分析:
{}' ',lst
然后 fn 查找分隔符并使用它来构建单词向量:
{(⍵=' ')⊂⍵}' ',lst
┌─────┬───┬──┬───────┐
│ this│ is│ a│ string│
└─────┴───┴──┴───────┘
让我们删除空白:
{1↓¨(⍵=' ')⊂⍵}' ',lst
┌────┬──┬─┬──────┐
│this│is│a│string│
└────┴──┴─┴──────┘
然后你“只”需要计算每个向量的长度:
{1↓¨(⍵=' ')⊂⍵}' ',lst
这是您请求的直接实现。但是,如果您对子字符串本身不感兴趣,而只对“非空白段”的长度感兴趣,则更“APLy”的解决方案可能是使用布尔值(通常最有效):
lst=' '
0 0 0 0 1 0 0 1 0 1 0 0 0 0 0 0
所以那些是分隔符的位置 - 它们出现在哪里?
⍸lst=' '
5 8 10
但是我们也需要一个尾随空格 - 否则我们会丢失文本的结尾:
⍸' '=lst,' '
5 8 10 17
所以这些 ( minus the positions of the preceeding blank
) 应该给出段的长度:
{¯1+⍵-0,¯1↓⍵}⍸' '=lst,' '
4 2 1 6
这仍然有些幼稚,可以用更高级的方式表达——我把它作为“读者练习”;-)
For how to find the longhest word in a string i would use, in NARS APL the function
f←{v/⍨k=⌈/k←≢¨v←(⍵≠' ')⊂⍵}
example to use
f 'this is a string thesam'
string thesam
explenation
{v/⍨k=⌈/k←≢¨v←(⍵≠' ')⊂⍵}
v←(⍵≠' ')⊂⍵ split the string where are the spaces and assign result to v
k←≢¨v to each element of v find the lenght, the result will be a vector
that has same lenght of v saved in k
⌈/k this find max in k
k= and this for each element of k return 0 if it is not max, 1 if it is max
v/⍨ this return the element of v that are max