Prolog: how to convert string to integer? - string

So as the title says - how do you convert a string into an integer?
the idea is something like this:
convert(String,Integer).
examples:
convert('1',1).
convert('33',33).
I'm using swi prolog

Use atom_number/2.
E.g:
atom_number('123', X).
X = 123.

Assuming you really meant a string and not an atom, use number_codes.
?- number_codes(11, "11").
true.
?- number_codes(11, Str).
Str = [49, 49]. % ASCII/UTF-8
?- number_codes(N, "11").
N = 11.

Perhaps use of atom_codes(?Atom, ?String) and number_chars(?Number, ?CharList) would do it.

Quite an old, but there is a predicate in SWI Prolog: number_string(N, S).
Docs
number_string(123, S).
S = "123".
For those who are still looking for it.

A simple example using Visual Prolog 10
==============================
% UNS-EPISI-LAB-IA
implement main
open core
clauses
run() :-
console::write("Valor de A? "),
A = console::readLine(),
console::write("Valor de B? "),
B = console::readLine(),
Areal = toTerm(real, A),
Breal = toTerm(real, B),
console::write("A + B = ", Areal + Breal),
_ = console::readChar().
end implement main
goal
console::runUtf8(main::run).

in Visual Prolog convert:
X=toTerm(real,H).
real/integer/unsigned...

Related

How to handle simple inputs in Kattis with F#?

I am very new to F# and Kattis. I have tried this simple problem "Which is greater" at Kattis. Link is here: https://open.kattis.com/problems/whichisgreater
I have tried with this code:
open System
let a = Console.Read()
let b = Console.Read()
if a > b then Console.WriteLine "1" else Console.WriteLine "0"
But I still get wrong answer. Anybody who can help on how to handle inputs and outputs in Kattis for F#? Maybe some simple examples can be made available?
The following is accepted by Kattis:
open System
let line = Console.ReadLine().Split ' '
let a = int64 line.[0]
let b = int64 line.[1]
Console.WriteLine(if a > b then 1 else 0)
Here, we read the line, split it on a space character into two numbers, compare them and print the required result.
It looks like they're using an old version of the F# compiler, so you have to specify an explicit entry point. Here's their sample F# solution for a different problem:
open System
[<EntryPoint>]
let main argv =
(fun _ -> Console.ReadLine()) |>
Seq.initInfinite |>
Seq.takeWhile ((<>) null) |>
Seq.iter
(fun (s : string) ->
let arr = s.Split([|' '|])
let a = int64 arr.[0]
let b = int64 arr.[1]
/// solve test case and output answer
printfn "%d" (abs (a - b))
)
0
I think that should give you enough info to solve the "which is greater" problem you're looking at. (Note that Console.Read only reads a single character, so it's not what you want for this problem. Instead, you probably want to read in the entire line, then split it into two strings at the blank space, then convert each of those strings into an integer. Coincidentally, the sample code I pasted above does something similar.)

How to get int from float in picat?

I try to to read a line as string from console (stdin) in picat and get its half:
main =>
L = read_line(),
B = L.length/2,
S = L.slice(1,B),
println(S).
crashes with error(integer_expected(2.0),slice)
when int used instead of B - no crash. So how to turn B into integer?
you could use built-in function such as floor, round or ceiling from math module (more functions here). So you could modify your code like this:
main =>
L = read_line(),
B = round(L.length/2),
S = L.slice(1,B),
println(S).
Try either using integer(..) function to convert L.length/2 to integer or use to_integer() function....should do it for you.
type inference plays an essential role in functional evaluation. (/ /2) it's a floating point arithmetic operator, but slice/2 expects an integer. So you should instead use (// /2).
Picat> L=read_line(),println(L.slice(1,L.length//2)).
123456789
1234
L = ['1','2','3','4','5','6','7','8','9']
yes

how to compare strings in prolog

I want to write a program in prolog that compares two strings or string lists. I want achieve the following:
if StringList A == StringList B
{
do this
}
else
do something else
How can I achieve this?
What do you mean by do this? It hard to implement doing somewhat in Prolog, because all that you've got is facts and predicates.
?- (string1 = string2, X=1); (string1 \= string2, X=2).
X = 2.
Here's how you'd do it in a single line:
...
(A = B -> do this ; do something else)
...
/*SWI prolog code*/
string1(progga).
string2(ikra).
go:-
write("Enter your name"),
nl,
read(X),nl,
string1(Y),
X=#=Y,nl, write("Matched");
write("not Matched"),go2.
/*Another way to*/
go2:-
string1(A),
string2(B),
A=#=B,nl, write("Matched");
write("not Matched").

F#: Remove the first N characters from a string?

I'm trying to write some code to remove the first N characters in a string. I could have done this in an imperative manner already, but I would like to see it done in the spirit of functional programming. Being new to F# and functional programming, I'm having some trouble...
"Hello world".[n..];;
As #Jeff has shown, you can do this in six characters, so this is not necessarily the best question to ask to see how to "do it in the spirit of functional programming".
I show another way, which is not particularly "functional" (as it uses arrays, but at least it doesn't mutate any), but at least shows a set of steps.
let s = "Hello, world!"
// get array of chars
let a = s.ToCharArray()
// get sub array (start char 7, 5 long)
let a2 = Array.sub a 7 5
// make new string
let s2 = new string(a2)
printfn "-%s-" s2 // -world-
"Hello world".Substring 3
let rec remove_first_n (str:string) (n:int) =
match str, n with
| _, n when n <= 0 -> str
| "", _ -> ""
| _ -> remove_first_n (str.Remove(0,1)) (n-1)
Another way to do it (not particularly functional either). In fact it uses features of both world: mutation and lambda:
let remove_first_n (s:string) (n:int) =
let arr = Array.create (s.Length-n) '0'
String.iteri (fun i c -> if i>=n then arr.[i-n] <- c else ()) s
new string(arr)
That being said, I think the best way is Jeff's solution.
One more thing to keep in mind is that Strings are immutable in .NET (a string value cannot be modified once built) and that F# strings are actually .NET Strings.

Simple haskell string manage

Theres is a little problem I want to solve with Haskell:
let substitute a function that change all of the wildcards in a string for one concrete parameter. The function has de signature of:
subs :: String -> String -> String -> String
-- example:
-- subs 'x' "x^3 + x + sin(x)" "6.2" will generate
-- "6.2^3 + 6.2 + sin(6.2)"
You could use the Text.Regex package.
Your example might look something like this:
import Text.Regex(mkRegex, subRegex)
subs :: String -> String -> String -> String
subs wildcard input value = subRegex (mkRegex wildcard) input value
See http://bluebones.net/2007/01/replace-in-haskell/ for an example which looks exactly as the piece of code you are looking for.
You can use text-format-simple library for such cases:
import Text.Format
format "{0}^3 + {0} + sin({0})" ["6.2"]
Use regular expressions (Text.Regex.Posix) and search-replace for /\Wx\W/ (Perl notation). Simply replacing x to 6.2 will bring you trouble with x + quux.
Haskell Regex Replace for more information (I think this should be imported to SO.
For extra hard-core you could parse your expression as AST and do the replacement on that level.

Resources