Scheme check between multiple strings - string

Out of practice to make myself more familiar with the scheme interface, I'm trying to write a procedure in Dr. Racket (though compatible with MIT Scheme) that checks between various different strings given and returns the appropriate strings depending on what is provided. What I have so far is this:
(define (conversation input)
(cond ((eq? (or "hello Racket" "hi Racket" "what's up, Racket?"
"hey Racket" "what's happening, Racket?") input) "hey coder")
(else "no hablo ingles.")))
*the space in between the strings is just so it will fit on here. It's one long statement in the interpreter.
The desired effect is that if I put in:
(conversation "hello Racket")
(conversation "hi Racket")
(conversation "hey Racket")
They will all return the same result, which is "hey coder". However, that is not what's happening. The only one that returns "hey coder" is (conversation "hello Racket"). All the rest return "no hable ingles." As with many other aspects of the language, I'm not all too savvy with strings in scheme. I'm fairly certain that the problem lies within the or statement, though I wouldn't know of the alternatives that would work in this context. I've tried looking up solutions, though I haven't run across anything that fits this type of description. Does anyone know of any alternatives to the code that would work?

or takes a list of arguments and checks whether any of its arguments are "truthy" (that is not #f). If so, it returns the first of its arguments that is truthy. If not, it returns #f. So (or "string1" "string2" ...) simply returns "string1". So all you're doing is checking whether the given string equals "hello Racket" and ignoring the other options (you might object here that it doesn't work for "hello Racket" either - I'll get to that). What you want to be doing is to give whole conditions to or, not just the strings. So it should look like (or (eq? "string1" input) (eq? "string2" input) ...).
However this doesn't work either. Why not? Because eq? is the wrong function to use to compare strings. It only returns true if two strings reside in the same location in memory. If two strings reside in different memory locations, but have the same contents, it returns #f. This is also why your current code returns #f for "hello Racket". What you should be using is equal?, which compares the contents of the strings.
This should work now, but it's a bit clunky - repeating the call to equal? for every possible string. A nicer approach would be to create a list with the valid strings and then check whether the input string is contained in the list using the member function.

You can achieve the effect that you intended using the member procedure and a list of possible options:
member locates the first element of lst that is equal? to v. If such an element exists, the tail of lst starting with that element is returned. Otherwise, the result is #f.
This is what I mean:
(define (conversation input)
(cond ((member input '("hello Racket" "hi Racket" "what's up, Racket?"
"hey Racket" "what's happening, Racket?"))
"hey coder")
(else "no hablo ingles.")))

Related

Way to find a number at the end of a string in Smalltalk

I have different commands my program is reading in (i.e., print, count, min, max, etc.). These words can also include a number at the end of them (i.e., print3, count1, min2, max6, etc.). I'm trying to figure out a way to extract the command and the number so that I can use both in my code.
I'm struggling to figure out a way to find the last element in the string in order to extract it, in Smalltalk.
You didn't told which incarnation of Smalltalk you use, so I will explain what I would do in Pharo, that is the one I'm familiar with.
As someone that is playing with Pharo a few months at most, I can tell you the sheer amount of classes and methods available can feel overpowering at first, but the environment actually makes easy to find things. For example, when you know the exact input and output you want, but doesn't know if a method already exists somewhere, or its name, the Finder actually allow you to search by giving a example. You can open it in the world menu, as shown bellow:
By default it seeks selectors (method names) matching your input terms:
But this default is not what we need right now, so you must change the option in the upper right box to "Examples", and type in the search field a example of the input, followed by the output you want, both separated by a ".". The input example I used was the string 'max6', followed by the desired result, the number 6. Pharo then gives me a list of methods that match that:
To get what would return us the text part, you can make a new search, changing the example output from number 6 to the string 'max':
Fortunately there is several built-in methods matching the description of your problem.
There are more elegant ways, I suppose, but you can make use of the fact that String>>#asNumber only parses the part it can recognize. So you can do
'print31' reversed asNumber asString reversed asNumber
to give you 31. That only works if there actually is a number at the end.
This is one of those cases where we can presume the input data has a specific form, ie, the only numbers appear at the end of the string, and you want all those numbers. In that case it's not too hard to do, really, just:
numText := 'Kalahari78' select: [ :each | each isDigit ].
num := numText asInteger. "78"
To get the rest of the string without the digits, you can just use this:
'Kalahari78' withoutTrailingDigits. "Kalahari"6
As some of the Pharo "OGs" pointed out, you can take a look at the String class (just type CMD-Return, type in String, hit Return) and you will find an amazing number of methods for all kinds of things. Usually you can get some ideas from those. But then there are times when you really just need an answer!

How to compare Strings and put it into another program?

i´ve got small problem and before I spend even more time in trying to solve it i´d like to know if what I want to do is even possible ( and maybe input on how to do it^^).
My problem:
I want to take some text and then split it into different strings at every whitespace (for example "Hello my name is whatever" into "Hello" "my" "name" "is" "whatever").
Then I want to set every string with it´s own variable so that I get something alike to a= "Hello" b= "my" and so on. Then I want to compare the strings with other strings (the idea is to get addresses from applications without having to search through them so I thought I could copy a telephone book to define names and so on) and set matching input to variables like Firstname , LastName and street.
Then, and here comes the "I´d like to know if it´s possible" part I want it to put it into our database, this means I want it to copy the string into a text field and then to go to the next field via tab. I´ve done something like this before with AutoIT but i´ve got no idea how to tell AutoIT whats inside the strings so I guess it must be done through the programm itself.
I´ve got a little bit of experience with c++, python and BATCH files so it would be nice if anyone could tell me if this can even be done using those languages (and I fear C++ can do it and I´m just to stupid to do so).
Thanks in advance.
Splitting a string is very simple, there is usually a built in method called .split() which will help you, the method varies from language to language.
When you've done a split, it will be assigned to an array, you can then use an index to get the variables, for example you'd have:
var str = "Hello, my name is Bob";
var split = str.split(" ");
print split[0]; // is "Hello,"
print split[1]; // is "my" etc
You can also use JSON to return data so you could have an output like
print split["LastName"];
What you're asking for is defiantly possible.
Some links that could be useful:
Split a string in C++?
https://code.google.com/p/cpp-json/

Basic Printing with Elixir - IO.puts error: ** (ArgumentError) argument error (stdlib) :io.put_chars(#PID

Here's the program I'm trying to run for Elixir 1.0.3:
IO.puts "putstest"
div2 = fn inputnum ->
[:a, inputnum/4, inputnum/7, inputnum/5.0, inputnum/7, inputnum*88]
end
myoutput = div2.(300.0)
IO.puts myoutput
I added the :a atom in case Elixir was doing some sort of implicit casting.
I'm sort of new to Elixir. I keep getting the following error when I run the code above by $ elixir putztestzorz.exs:
putstest
** (ArgumentError) argument error
(stdlib) :io.put_chars(#PID<0.24.0>, :unicode, [[:a, 75.0, 42.857142857142854, 60.0, 42.857142857142854, 2.64e4], 10])
(elixir) lib/code.ex:316: Code.require_file/2
I checked the IO documentation, but neither IO.stream (Converts the io device into a IO.Stream, changed the last line to IO.stream output) nor IO.write (Writes the given argument to the given device, changed the last line to IO.write :stdout, output) seem to do the trick.
I don't want to keep just guessing, here, and I seem to not quite understand what the function is supposed to be doing.
Is there an analogue to Python's print() that will just, well, work?
Do I need to cast the list, or something?
I'm probably missing something really simple, here, but I don't want to just guess my way down the list of IO handling functions.
(P.S. The documentation keeps talking about a Process.group_leader. I don't plan to do much with this yet, but is there a way to put it in context for this sort of thing? I keep imagining Red Leader from Star Wars.)
The problem is that IO.puts cannot handle arbitrary lists, hence the ArgumentError. The only type of list it can handle are character lists, or single quoted strings. This is the reason why the function matches the list argument successfully, but later blows up deep down inside the library. You basically have two alternatives:
Use IO.inspect to quickly debug any value to stdout.
IO.inspect myoutput
Use a for comprehension together with Erlang's :io.format to explicitly format the output, much like printf. The :a will probably throw an error, but if you remove it, the following should work:
for x <- myoutput do
:io.format "~.2f~n", [x]
end
Note that ~.2f prints the values with two digits after the comma. ~n adds the newline.

String Comparison in python by ignoring the Mixed Case

I am actually trying to validate a string which is mixed case. Example:
WeLComE: this is my default string -- string1.
I am retrieving same string from some other method which is coming as welcome (lower case) -- string2.
When I am comparing both of them and keeping an if test for both the strings to match. But as these both are in different case, I am unable to go inside the if block. So I am doing
if string2 == string1.lower():
which is working for me.
But is there any other way which can ignore the case for the strings and compare them.
Any other method?
Your example is fine. If you are sure that string2 is always in lower case, you can certainly compare with
if string2 == string1.lower():
Or else go with
if string2.lower() == string1.lower():
If you absolutely need a different approach, go with
import re
if re.match("^welcome$", "WeLcOmE", re.I)

How to write a self reproducing code (prints the source on exec)?

I have seen a lot of C/C++ based solutions to this problem where we have to write a program that upon execution prints its own source.
some solutions --
http://www.cprogramming.com/challenges/solutions/self_print.html
Quine Page solution in many languages
There are many more solutions on the net, each different from the other. I wonder how do we approach to such a problem, what goes inside the mind of the one who solves it. Lend me some insights into this problem... While solutions in interpreted languages like perl, php, ruby, etc might be easy... i would like to know how does one go about designing it in compiled languages...
Aside from cheating¹ there is no difference between compiled and interpreted languages.
The generic approach to quines is quite easy. First, whatever the program looks like, at some point it has to print something:
print ...
However, what should it print? Itself. So it needs to print the "print" command:
print "print ..."
What should it print next? Well, in the mean time the program grew, so it needs to print the string starting with "print", too:
print "print \"print ...\""
Now the program grew again, so there's again more to print:
print "print \"print \\\"...\\\"\""
And so on.
With every added code there's more code to print.
This approach is getting nowhere,
but it reveals an interesting pattern:
The string "print \"" is repeated over and over again.
It would be nice to put the repeating part
into a variable:
a = "print \""
print a
However, the program just changed,
so we need to adjust a:
a = "a = ...\nprint a"
print a
When we now try to fill in the "...",
we run into the same problems as before.
Ultimately, we want to write something like this:
a = "a = " + (quoted contents of a) + "\nprint a"
print a
But that is not possible,
because even if we had such a function quoted() for quoting,
there's still the problem that we define a in terms of itself:
a = "a = " + quoted(a) + "\nprint a"
print a
So the only thing we can do is putting a place holder into a:
a = "a = #\nprint a"
print a
And that's the whole trick!
Anything else is now clear.
Simply replace the place holder
with the quoted contents of a:
a = "a = #\nprint a"
print a.replace("#", quoted(a))
Since we have changed the code,
we need to adjust the string:
a = "a = #\nprint a.replace(\"#\", quoted(a))"
print a.replace("#", quoted(a))
And that's it!
All quines in all languages work that way
(except the cheating ones).
Well, you should ensure that you replace only
the first occurence of the place holder.
And if you use a second place holder,
you can avoid needing to quote the string.
But those are minor issues
and easy to solve.
If fact, the realization of quoted() and replace()
are the only details in which the various quines really differ.
¹ by making the program read its source file
There are a couple of different strategies to writing quines. The obvious one is to just write code that opens the code and prints it out. But the more interesting ones involve language features that allow for self-embedding, like the %s-style printf feature in many languages. You have to figure out how to embed something so that it ends up resolving to the request to be embedded. I suspect, like palindromes, a lot of trial and error is involved.
The usual approach (when you can't cheat*) is to write something that encodes its source in a string constant, then prints out that constant twice: Once as a string literal, and once as code. That gets around the "every time I write a line of code, I have to write another to print it out!" problem.
'Cheating' includes:
- Using an interpreted language and simply loading the source and printing it
- 0-byte long files, which are valid in some languages, such as C.
For fun, I came up with one in Scheme, which I was pretty proud of for about 5 minutes until I discovered has been discovered before. Anyways, there's a slight modification to the "rules" of the game to better count for the duality of data and code in Lisp: instead of printing out the source of the program, it's an S-expression that returns itself:
((lambda (x) (list x `',x)) '(lambda (x) (list x `',x)))
The one on Wikipedia has the same concept, but with a slightly different (more verbose) mechanism for quoting. I like mine better though.
One idea to think about encoding and how to give something a double meaning so that it can be used to output something in a couple of forms. There is also the cavaet that this type of problem comes with restrictions to make it harder as without any rules other than the program output itself, the empty program is a solution.
How about actually reading and printing your source code? Its not difficult at all!! Heres one in php:
<?php
{
header("Content-Type: text/plain");
$f=fopen("5.php","r");
while(!feof($f))
{
echo fgetc($f);
}
fclose($f);
}
?>
In python, you can write:
s='c=chr(39);print"s="+c+s+c+";"+s';c=chr(39);print"s="+c+s+c+";"+s
inspired from this self printing pseudo-code:
Print the following line twice, the second time with quotes.
"Print the following line twice, the second time with quotes."
I've done a AS3 example for those interested in this
var program = "var program = #; function main(){trace(program.replace('#',
String.fromCharCode(34) + program + String.fromCharCode(34)))} main()";
function main(){
trace(program.replace('#', String.fromCharCode(34) + program + String.fromCharCode(34)))
}
main()
In bash it is really easy
touch test; chmod oug+x test; ./test
Empty file, Empty output
In ruby:
puts File.read(_ _ FILE _ _)

Resources