Phrase reversals: Difference between revisions

Content deleted Content added
Added EchoLisp
Hout (talk | contribs)
Line 177:
 
</pre>
 
=={{header|AppleScript}}==
 
AppleScript has a very small and patchy library of primitive functions. To accumulate a larger and more coherent library, which includes some higher order functions, we can try to overcome two architectural weaknesses: 1. Built-in functions have a different type from user functions, and 2. user functions are second class properties of (first class) script objects.
 
Here is a simple illustration of unifying (and elevating) the function type by wrapping the built-in functions in user handlers (perhaps making some of them polymorphic where needed), and also obtaining first class status for ordinary user handler functions by 'lifting' them (for use as arguments in higher order functions) into a first class script object. (This process can be inlined, or abstracted out to an '''mReturn''' or '''mInject''' function).
 
<lang AppleScript>on run {}
set phrase to "rosetta code phrase reversal"
intercalate(linefeed, {_reverse(phrase), reverseEachWord(phrase), reverseWordOrder(phrase)})
end run
 
-- Text -> Text
on _reverse(xs)
if class of xs is text then
return (reverse of characters of xs) as text
else
return reverse of xs
end if
end _reverse
 
-- Text -> Text
on _words(str)
return words of str
end _words
 
--Text -> Text
on reverseEachWord(str)
return unwords(map(_words(str), _reverse))
end reverseEachWord
 
--Text -> Text
on reverseWordOrder(str)
return unwords(_reverse(_words(str)))
end reverseWordOrder
 
-- [a] -> (a -> b) -> [b]
on map(xs, f)
set mf to mReturn(f)
set lst to {}
set lng to length of xs
repeat with i from 1 to lng
set end of lst to mf's call(item i of xs, i, xs)
end repeat
return lst
end map
 
-- lift 2nd class function into 1st class wrapper
-- handler function --> first class script object
on mReturn(f)
script mf
property call : f
end script
end mReturn
 
-- [Text] -> Text
on unwords(lstWords)
set {dlm, my text item delimiters} to {my text item delimiters, space}
set strWords to lstWords as text
set my text item delimiters to dlm
return strWords
end unwords
 
-- Text -> Text -> [Text]
on splitOn(strDelim, strMain)
set {dlm, my text item delimiters} to {my text item delimiters, strDelim}
set lstParts to text items of strMain
set my text item delimiters to dlm
return lstParts
end splitOn
 
-- Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate</lang>
{{out}}
<pre>"lasrever esarhp edoc attesor
attesor edoc esarhp lasrever
reversal phrase code rosetta"</pre>
 
=={{header|AWK}}==