How to convert ints to strings in SML recursively? - recursion

I made a very small program which takes an int and converts it into string in SML:
fun int2str i =
if i < 0 then "~" ^ Int.toString (~i)
else Int.toString i;
int2str(~1234) --> "~1234"
int2str(1234) --> "1234"
I have been struggling immensely to accomplish this in a recursive way. Any help? Additionally, I had to take a string and convert it into an int which I finished through stackOverflow help in general, but the '~' screws everything up as well; however this was able to be finished recursively.

I'm not entirely sure why you need to do this recursively since calling Int.toString on any int will produce the desired result (even if it's negative) but you can also do:
fun helper 0 = "" | helper n = helper (Int.div(n, 10)) ^ Int.toString (Int.mod (n, 10));
fun int2str n = if n < 0 then "~" ^ helper(~n) else if n = 0 then "0" else helper(n);
Modding by 10 will get the last digit and integer dividing by 10 will cut off the last digit so this should get you your desired results in a recursive manner.

Related

How to fix type error in F# function arguments

I have a program that is trying to take in a list of ints and return a int list that has all the odd numbers from it, i'm new to functional programming and am trying to learn it with F#. When I try and call the removeEvens in main it gives me this error
Error FS0001 This expression was expected to have type
'int list -> 'a'
but here has type
''b list'
and here is my code
open System
let rec removeEvens arr count ret =
if count < 0 then
ret
else
if count % 2 = 0 then
removeEvens arr (count + 1) ret
else
removeEvens arr (count + 1) (arr[count] :: ret)
let rec printResults arr count =
if count > 0 then
printfn "%d" (arr[count])
printResults arr (count + 1)
[<EntryPoint>]
let main argv =
printResults (removeEvens [0 .. 100] 0 []) 0
0
Syntactically, the only problem here is that the index operator is missing a . character. So you want arr.[count] instead of arr[count] (which the F# compiler thinks is the application of a function called arr to a singleton list, hence the compiler error). In order to use indexing, you'll also need to explicitly annotate your arr value as a list, like this: (arr : List<_>).
Semantically, you should be aware that indexing into lists in this way is inefficient, but that's a separate issue. I suggest instead that a more elegant way to remove even numbers from a list is to consider only the head element of the list inside your recursive function.

Is there a way to display this only once?

I wrote this sml function that allows me to display the first 5 columns of the Ascii table.
fun radix (n, base) =
let
val b = size base
val digit = fn n => str (String.sub (base, n))
val radix' =
fn (true, n) => digit n
| (false, n) => radix (n div b, base) ^ digit (n mod b)
in
radix' (n < b, n)
end;
val n = 255;
val charList = List.tabulate(n+1,
fn x => print(
"DEC"^"\t"^"OCT"^"\t"^"HEX"^"\t"^"BIN"^"\t"^"Symbol"^"\n"^
Int.toString(x)^"\t"^
radix (x, "01234567")^"\t"^
radix (x, "0123456789abcdef")^"\t"^
radix (x, "01")^"\t"^
Char.toCString(chr(x))^"\t"
)
);
But I want the header : "DEC"^"\t"^"OCT"^"\t"^"HEX"^"\t"^"BIN"^"\t"^"Symbol" to be displayed only once at the beginning, but I can't do it. Does anyone know a way to do it?
On the other hand I would like to do without the resursive call of the "radix" function. Is that possible? And is it a wise way to write this function?
I want the header : "DEC"... to be displayed only once at the beginning
Currently the header displays multiple times because it is being printed inside of List.tabulate's function, once for each number in the table. So you can move printing the header outside of this function and into a parent function.
For clarity I might also move the printing of an individual character into a separate function. (I think you have indented the code in your charList very nicely, but if a function does more than one thing, it is doing too many things.)
E.g.
fun printChar (i : int) =
print (Int.toString i ^ ...)
fun printTable () =
( print "DEC\tOCT\tHEX\tBIN\tSymbol\n"
; List.tabulate (256, printChar)
; () (* why this? *)
)
It is very cool that you found Char.toCString which is safe compared to simply printing any character. It seems to give some pretty good names for e.g. \t and \n, but hardly for every function. So if you really want to spice up your table, you could add a helper function,
fun prettyName character =
if Char.isPrint character
then ...
else case ord character of
0 => "NUL (null)"
| 1 => "SOH (start of heading)"
| 2 => "STX (start of text)"
| ...
and use that instead of Char.toCString.
Whether to print a character itself or some description of it might be up to Char.isPrint.
I would like to do without the resursive call of the "radix" function.
Is that possible?
And is it a wise way to write this function?
You would need something equivalent to your radix function either way.
Sure, it seems okay. You could shorten it a bit, but the general approach is good.
You have avoided list recursion by doing String.sub constant lookups. That's great.

Get a number from an array of digits

To split a number into digits in a given base, Julia has the digits() function:
julia> digits(36, base = 4)
3-element Array{Int64,1}:
0
1
2
What's the reverse operation? If you have an array of digits and the base, is there a built-in way to convert that to a number? I could print the array to a string and use parse(), but that sounds inefficient, and also wouldn't work for bases > 10.
The previous answers are correct, but there is also the matter of efficiency:
sum([x[k]*base^(k-1) for k=1:length(x)])
collects the numbers into an array before summing, which causes unnecessary allocations. Skip the brackets to get better performance:
sum(x[k]*base^(k-1) for k in 1:length(x))
This also allocates an array before summing: sum(d.*4 .^(0:(length(d)-1)))
If you really want good performance, though, write a loop and avoid repeated exponentiation:
function undigit(d; base=10)
s = zero(eltype(d))
mult = one(eltype(d))
for val in d
s += val * mult
mult *= base
end
return s
end
This has one extra unnecessary multiplication, you could try to figure out some way of skipping that. But the performance is 10-15x better than the other approaches in my tests, and has zero allocations.
Edit: There's actually a slight risk to the type handling above. If the input vector and base have different integer types, you can get a type instability. This code should behave better:
function undigits(d; base=10)
(s, b) = promote(zero(eltype(d)), base)
mult = one(s)
for val in d
s += val * mult
mult *= b
end
return s
end
The answer seems to be written directly within the documentation of digits:
help?> digits
search: digits digits! ndigits isdigit isxdigit disable_sigint
digits([T<:Integer], n::Integer; base::T = 10, pad::Integer = 1)
Return an array with element type T (default Int) of the digits of n in the given base,
optionally padded with zeros to a specified size. More significant digits are at higher
indices, such that n == sum([digits[k]*base^(k-1) for k=1:length(digits)]).
So for your case this will work:
julia> d = digits(36, base = 4);
julia> sum([d[k]*4^(k-1) for k=1:length(d)])
36
And the above code can be shortened with the dot operator:
julia> sum(d.*4 .^(0:(length(d)-1)))
36
Using foldr and muladd for maximum conciseness and efficiency
undigits(d; base = 10) = foldr((a, b) -> muladd(base, b, a), d, init=0)

Sum of the digits of a number?

I am a newbie to programming .here I have been solving a simple problem in functional programming (OZ) which is finding the sum of the Digits of a 6 digit positive integer.
Example:- if n = 123456 then
output = 1+2+3+4+5+6 which is 21.
here I found a solution like below
fun {SumDigits6 N}
{SumDigits (N Div 1000) + SumDigits (N mod 1000)}
end
and it says the argument (N Div 1000) gives first 3 digits and the argument (N mod 1000) gives us last 3 digits. and yes I getting the correct solution but my Doubt is how could they giving correct solutions. I mean in given example isn't (N Div 1000) of 123456 gives 123 right not 1+2+3 and similarly (N mod 1000) of123456 gives us 456 not 4+5+6 right ?. in that case, the answer should be 123+456 which is equals to 579 not 21 right ? what Iam missing here.I apologize for asking such simple question but any help would be appreciated.
Thank you :)
You are missing the most important thing here.
It is supposed to happen in a loop and each time the value of N changes.
For example
in the first iteration
the Div gives 1 and mod gives 6 so you add 1 and 6 and store the result and the number is also modified (it becomes 2345)
in the second iteration
the div gives 2 and mod gives 5 you add 2+5+previous result and the number is also modified..
This goes on till the number becomes zero
Your function is recursive, so every time the number get smaller, untill is just 0, then it goes back summing all the partial result. You can do it with an accumulator to store the result, in this simple way:
declare
fun {SumDigit N Accumulator}
if N==0 then Accumulator
else {SumDigit (N div 10) Accumulator+(N mod 10)}
end
end
{Browse {SumDigit 123456 0}}
i think the most elegant way is the function --
static int SumOfDigit(int n)
{
if (n < 10) return n;
return SumOfDigit(SumOfDigit(n/10)+n%10);
}
simple and true :-)
int main()
{
int n,m,d,s=0;
scanf("%d",&n);
m=n;
while(m!=0)
{
d=m%10;
s=s+d;
m=m/10;
}
printf("Sum of digits of %d is %d",n,s);
}

Recursive function to repeat string in OCaml

I am absolute OCaml beginner. I want to create a function that repeats characters 20 times.
This is the function, but it does not work because of an error.
let string20 s =
let n = 20 in
s ^ string20 s (n - 1);;
string20 "u";;
I want to run like this
# string20 "u"
- : string = "uuuuuuuuuuuuuuuuuuuu"
Your function string20 takes one parameter but you are calling it recursively with 2 parameters.
The basic ideas are in there, but not quite in the right form. One way to proceed is to separate out the 2-parameter function as a separate "helper" function. As #PierreG points out, you'll need to delcare the helper function as a recursive function.
let rec string n s =
if n = 0 then "" else s ^ string (n - 1) s
let string20 = string 20
It is a common pattern to separate a function into a "fixed" part and inductive part. In this case, a nested helper function is needed to do the real recursive work in a new scope while we want to fix an input string s as a constant so we can use to append to s2. s2 is an accumulator that build up the train of strings over time while c is an inductor counting down to 1 toward the base case.
let repeat s n =
let rec helper s1 n1 =
if n1 = 0 then s1 else helper (s1 ^ s) (n1 - 1)
in helper "" n
A non-tail call versions is more straightforward since you won't need a helper function at all:
let rec repeat s n =
if n = 0 then "" else s ^ repeat s (n - 1)
On the side note, one very fun thing about a functional language with first-class functions like Ocaml is currying (or partial application). In this case you can create a function named repeat that takes two arguments n of type int and s of type string as above and partially apply it to either n or s like this:
# (* top-level *)
# let repeat_foo = repeat "foo";;
# repeat_foo 5;;
- : bytes = "foofoofoofoofoo" (* top-level output *)
if the n argument was labeled as below:
let rec repeat ?(n = 0) s =
if n = 0 then "" else s ^ repeat s (n - 1)
The order of application can be exploited, making the function more flexible:
# (* top-level *)
# let repeat_10 = repeat ~n:10;;
# repeat_10 "foo";;
- : bytes = "foofoofoofoofoofoofoofoofoofoo" (* top-level output *)
See my post Currying Exercise in JavaScript (though it is in JavaScript but pretty simple to follow) and this lambda calculus primer.
Recursive functions in Ocaml are defined with let rec
As pointed out in the comments you've defined your function to take one parameter but you're trying to recursively call with two.
You probably want something like this:
let rec stringn s n =
match n with
1 -> s
| _ -> s ^ stringn s (n - 1)
;;

Resources