Merlin
Merlin

Reputation: 97

OCaml - Strings (program)

I wanted to create a program that reads from standard input two ints separated by a space. So I though I could store them as a string. Then, I wanted to use something like String.get to obtain the 1st and the 3rd characters (the ints separated by space), and then print them as ints.

Here's my code so far (with syntax errors probably):

open Printf
open Scanf


let () = printf "String: "
let str = scanf "%s"


let char1 = String.get str 0
let char3 = String.get str 2

let () = printf "%d %d\n" char1 char3

I get compiler error.

File "string.ml", line 9, characters 23-26:
Error: This expression has type (string -> 'a) -> 'a
   but an expression was expected of type String

So I wanted to know how could I make this work? Is there a better way to do this program?

Upvotes: 0

Views: 56

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66818

The type of scanf "%s" is not what you think. The scanf family in OCaml takes parameters that are functions for handling inputs of the given type. So scanf "%s" takes a function as a parameter. Since you didn't pass the function, you end up with the complicated type string -> '_a -> '_a.

If you want the function to return the string unchanged, you can use the identity function:

# let id x = x ;;
val id : 'a -> 'a = <fun>

# let mystring = scanf "%s" id ;;
testing
val mystring : string = "testing"

The second problem in your code is that you're treating the type char as if it's the same as int.

# printf "%d" '3' ;;
Error: This expression has type char but an expression
   was expected of type int

If you want to convert a single digit to an int, you could use this function:

let int_of_char c = Char.code c - Char.code '0'

However, this isn't a very robust function.

It would probably be better to use scanf to do the conversion in the first place, which is in fact its main purpose.

# let myint = scanf " %d" id ;;
347
val myint : int = 347

Upvotes: 1

Related Questions