I'm new to ReasonML, but I read through most of the official documents. I could go through the casual trial and errors for this, but since I need to write codes in ReasonML right now, I'd like to know the best practices of iterating keys and values of reason record types.
What is the best practice of iterating record keys and values in Reasonml?
1.1k Views Asked by Sanghyun Kim At
2
There are 2 best solutions below
3
Shawn
On
Maybe I am not understanding the question or the use case. But as far as I know there is no way to iterate over key/value pairs of a record. You may want to use a different data model:
- hash table https://caml.inria.fr/pub/docs/manual-ocaml/libref/Hashtbl.html
- Js.Dict (if you're working in bucklescript/ReScript) https://rescript-lang.org/docs/manual/latest/api/js/dict
- a list of tuples
With a record all keys and value types are known so you can just write code to handle each one, no iteration needed.
Related Questions in RECORD
- Documentation comments for record types with primary constructors in C#
- Can not switch camera while recording with camera plugin, setDescription working but preview doesn't change
- Enforcing Instance Creation of Record Types Through Specific Methods in C#
- Flutter sound package file save and post api
- android how record video from media3 playerview surfaceview
- Java Record "toString()" mask sensitive fields
- Declaring a set of a set in Mosel
- Bunch of errors that aren't valid, probably because of formatting but I can't crack it
- Record Triggered Flow Error- failure to insert records
- Flutter record sound on background
- Question about Record Pointer as a Function Variable
- Convert record to string with custom delimiter
- How do I ensure my 2 procedures update the same record during the same session
- Record video in Next js socket io
- How to Instantiate a Custom Data Type with Record Syntax and Multiple Constructors
Related Questions in REASON
- Failure during standard install of Reason on MacOs (updated by author)
- Convert Json array to list of strings
- OCaml error: "The present constructor Function__webkit_gradient has a conjunctive type"
- Does genType library supports generating types from typescript to rescript/reasonml?
- How can I use react-datepicker in the ReScript app
- How to switch the type of an item in my type signature?
- Why is inserting this string into a record throwing an error?
- ReScript, TypeScript: Cannot find module '@rescript/react/src/ReactDOM.gen' or its corresponding type declarations
- Curry.js error when exporting a rescript function with more than 1 parameter using genType
- How do I use modulus operator in Reason React?
- Reasonml syntax meaning |
- How do I add an OCaml library reference to a Reason code file?
- How to use a JavaScript Material Design library in ReScript?
- Rescript Record: Key as Array
- Can VSCode extensions be written in ReasonML?
Related Questions in BUCKLESCRIPT
- What is the difference between option<t>=? and just =? in ReScript JSX?
- Convert Json array to list of strings
- Longident.flat error when trying to migrate a file from bucklescript to rescript
- Curry.js error when exporting a rescript function with more than 1 parameter using genType
- How do I implement hash functions for arbitrary record types in ReScript?
- Why can't I assign a 64bit integer to this field?
- How to read JSON with unknown key in ReasonML?
- How would I write a generic function to handle multiple record types in ReScript?
- Infinite Lists / Streams in ReScript
- How do you call an uncurried function with unit in ReScript/ReasonML?
- How can one iterate/map over a Js.Json.t that is an array?
- Is it possible to partially compile a Reason+React application?
- How to set a dynamic value as a Js.t key in ReScript?
- How to convert a Js.Dict.t to Js.t in ReScript?
- How do I use an unwrapped polymorphic variant [union type] in a type parameter?
Related Questions in RESCRIPT
- Commandline flag Rescript to throw error on build for warnings
- How do I use the modulus operator?
- What is the difference between option<t>=? and just =? in ReScript JSX?
- How to do Try-Finally in ReScript?
- Getting data from Rescript input fields
- Getting FormData with rescript
- CSS won't load when using CSS modules
- Creating a vs code extension using Rescript
- How to do ReactDOM.createRoot?
- Convert Json array to list of strings
- pass type to module for abstract data type
- Rescript manipulate JSON file
- Is a simple way to use `Belt.Set` (and others) fixing its type?
- Is there a way to convert curried functions to uncurried functions?
- Trying to decode an event using rescript-json-combinators
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
Popular # Hahtags
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
I fully agree with @Shawn that you should use a more appropriate data structure. A list of tuples, for example, is a nice and easy way to pass in a user-defined set of homogeneous key/value pairs:
If you need heterogeneous data I would suggest using a variant to specify the data type:
Alternatively you can use objects instead of records, which seems like what you actually want.
For the record, a record requires a pre-defined record type:
and this is how you construct them:
Objects on the other hand are structurally typed, meaning they don't require a pre-defined type, and you construct them slightly differently:
Notice that the keys are strings.
With objects you can use
Js.Obj.keysto get the keys:The problem now is getting the values. There is no
Js.ObjAPI for getting the values or entries because it would either be unsound or very impractical. To demonstrate that, let's try making it ourselves.We can easily write our own binding to
Object.entries:entrieshere is a function that takes any object and returns an array of tuples withstringkeys and values of a type that will be inferred based on how we use them. This is neither safe, because we don't know what the actual value types are, or particularly practical as it will be homogeneously typed. For example:You can use either of these
switchexpressions (with unexpected results and possible crashes at runtime), but not both together as there is no unboxedstring | inttype to be inferred in Reason.To get around this we can make the value an abstract type and use
Js.Types.classifyto safely get the actual underlying data type, akin to usingtypeofin JavaScript:This is completely safe but, as you can see, not very practical.
Finally, we can actually modify this slightly to use it safely with records as well, by relying on the fact that records are represented internally as JavaScript objects. All we need to do is not restrict
entriesto objects:This is still safe because all values are objects in JavaScript and we don't make any assumptions about the type of the values. If we try to use this with a primitive type we'll just get an empty array, and if we try to use it with an array we'll get the indexes as keys.
But because records need to be pre-defined this isn't going to be very useful. So all this said, I still suggest going with the list of tuples.
Note: This uses ReasonML syntax since that's what you asked for, but refers to the ReScript documentation, which uses the slightly different ReScript syntax, since the BuckleScript documentation has been taken down (Yeah it's a mess right now, I know. Hopefully it'll improve eventually.)