PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, September 16, 2022

[FIXED] How can I print the string value of something wrapped in another type in Ocaml?

 September 16, 2022     ocaml, printf, printing, types     No comments   

Issue

I'm attempting to use Printf.sprintf to print out a value that is within a type of multiple options

type tid = int

type lock = string

type rdwrlock = 
  | Rdlock of lock
  | Wrlock of lock

type rdwrlockid = rdwrlock * tid

Basically, I want to print out a rdwrlockid, which is (rdwrlock*tid) and I can print out the tid easily using the %d option in printf, but how do I access the string within the lock within the rdwrlock?


Solution

Sticking to your example it could be done as follows:

let y, z = (Rdlock "a", 1) in
Printf.printf "%d %s\n" z (match y with Rdlock r -> r | Wrlock w -> w)

It may be simplified a bit:

type lck = READ | WRITE
type lckid = lck * tid

let k, i = (READ, 1) in
Printf.printf "%d %s\n" i (match k with READ -> "R" | WRITE -> "W");

Or if you do need string representation of lock oftenly, you may write a helper function:

let string_of_lock k =
    match k with
    | READ  -> "R"
    | WRITE -> "W"

And then use it in printf:

Printf.printf "%d %s\n" i (string_of_lock k)


Answered By - barti_ddu
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing