diff options
| author | muqiuhan <[email protected]> | 2025-09-09 06:17:00 +0000 |
|---|---|---|
| committer | muqiuhan <[email protected]> | 2025-09-09 06:17:00 +0000 |
| commit | d5de65fdb1802cdf498d65d93397f290813c377c (patch) | |
| tree | 92fe61a76d20d1203203665d4b48e7f151f088bd /search.xml | |
| parent | 48efa2dfde7c263f84ee5bb0872747034908d607 (diff) | |
| download | blog-d5de65fdb1802cdf498d65d93397f290813c377c.tar.gz | |
deploy: 9665097f0fa0dae9f92123fac54d26c0818758a5
Diffstat (limited to 'search.xml')
| -rw-r--r-- | search.xml | 3024 |
1 files changed, 1813 insertions, 1211 deletions
@@ -7,30 +7,29 @@ <blockquote> <p>Note: these tips are not necessarily ordered by usefulness. For that matter, there might or might not be exactly 10 of them :)</p> </blockquote> -<h2 id="Tip-1-Use-fsx-Files-for-Interactive-Coding"><a href="#Tip-1-Use-fsx-Files-for-Interactive-Coding" class="headerlink" title="Tip 1: Use .fsx Files for Interactive Coding"></a>Tip 1: Use <code>.fsx</code> Files for Interactive Coding</h2><p>You can use the F# Interactive 2 ways: you can directly type code into FSI, the F# Interactive window, or you can write code in an <code>.fsx</code> file, and select pieces of the code you want to execute. I recommend the second approach, for at least two reasons. First, FSI is a very primitive environment, <code>.fsx</code> files provide a much richer experience (IntelliSense). Then this encourages writing clean scripts you can reuse later.</p> +<h2 id="Tip-1-Use-fsx-Files-for-Interactive-Coding"><a class="header-anchor" href="#Tip-1-Use-fsx-Files-for-Interactive-Coding">¶</a>Tip 1: Use <code>.fsx</code> Files for Interactive Coding</h2> +<p>You can use the F# Interactive 2 ways: you can directly type code into FSI, the F# Interactive window, or you can write code in an <code>.fsx</code> file, and select pieces of the code you want to execute. I recommend the second approach, for at least two reasons. First, FSI is a very primitive environment, <code>.fsx</code> files provide a much richer experience (IntelliSense). Then this encourages writing clean scripts you can reuse later.</p> <blockquote> <p>This is not specific to scripts, but… if you are on Visual Studio, do yourself a service and install the <a href="http://fsprojects.github.io/VisualFSharpPowerTools/">Visual F# Power Tools</a> - you’ll get nice things such as better code highlighting, refactoring, and more.</p> </blockquote> <p>To execute code interactively, simply type code in an <code>.fsx</code> file, select a block of code, and hit Alt + Enter. The selected code will be evaluated, and the result will show up in the FSI window. In Visual Studio, you can also select code and right-click “Execute in Interactive”, but shortcuts are way faster.</p> <blockquote> -<p>You can also execute a single-line with Alt + ‘. I rarely use this option, but this can save you time because you don’t need to select the entire line of code.</p> +<p>You can also execute a single-line with Alt + '. I rarely use this option, but this can save you time because you don’t need to select the entire line of code.</p> </blockquote> <blockquote> -<p>In case the keyboard shortcuts to send code to FSI do not work anymore (ReSharper used to over-write them in the past), you can reset them in Visual Studio, by going to Tools / Options / Environment / Keyboard. The 2 commands you need to map are EditorContextMenus.CodeWindow.ExecuteInInteractive and EditorContextMenus.CodeWindow.ExecuteLineInInteractive.</p> +<p>In case the keyboard shortcuts to send code to FSI do not work anymore (ReSharper used to over-write them in the past), you can reset them in Visual Studio, by going to Tools / Options / Environment / Keyboard. The 2 commands you need to map are EditorContextMenus.CodeWindow.ExecuteInInteractive and EditorContextMenus.CodeWindow.ExecuteLineInInteractive.</p> </blockquote> <p>You can also use these shortcuts from a regular <code>.fs</code> file, which can be handy if you want to validate that a piece of code is behaving the way you want.</p> <blockquote> <p>Interactive coding is by far my main usage for scripts - I use it extensively to prototype designs, run dumb tasks, or explore data or libraries. I realized recently that a few of my C# friends use LinqPad for the same purpose.</p> </blockquote> -<h2 id="Tip-2-What-is-it"><a href="#Tip-2-What-is-it" class="headerlink" title="Tip 2: What is it?"></a>Tip 2: What is <code>it</code>?</h2><p>While I encourage working primarily from <code>.fsx</code> files, the FSI window is also very helpful. I use it primarily for small verifications. For instance, I might have in my script file code like this:</p> +<h2 id="Tip-2-What-is-it"><a class="header-anchor" href="#Tip-2-What-is-it">¶</a>Tip 2: What is <code>it</code>?</h2> +<p>While I encourage working primarily from <code>.fsx</code> files, the FSI window is also very helpful. I use it primarily for small verifications. For instance, I might have in my script file code like this:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">let add x y =</span><br><span class="line"> x + y</span><br></pre></td></tr></table></figure> - <p>Once I send it for evaluation into FSI, I will see the following show up in FSI:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">val add : x:int -> y:int -> int</span><br><span class="line">></span><br></pre></td></tr></table></figure> - <p>My function <code>add</code> is now in memory, in my FSI session; I can start typing in the FSI window and use it:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">> add 1 2;;</span><br><span class="line">val it : int = 3</span><br><span class="line">></span><br></pre></td></tr></table></figure> - <p>Enter does not trigger execution in FSI. The <code>;;</code> indicates to FSI “Please execute everything I just typed, up to that point”. This is useful if you want to type multiple lines of code in FSI, and execute them as a block.</p> <blockquote> <p><code>it</code>: in our <code>add 1 2</code> example, the result showed up as <code>it</code>. We simply ran add, but didn’t assign the result to anything. <code>it</code> now contains the result, until we run another expression. If you want to re-use that value, you can assign it in FSI, by doing for instance <code>let x = it;;</code>.′</p> @@ -42,20 +41,20 @@ <p>FSI often shows an abbreviated version of values for large items. For instance, <code>[1..999]</code> will show up as <code>val it : int list = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 14; 15; 16; 17; 18; 19; 20; 21; 22; 23; 24; 25; 26; 27; 28; 29; 30; 31; 32; 33; 34; 35; 36; 37; 38; 39; 40; 41; 42; 43; 44; 45; 46; 47; 48; 49; 50; 51; 52; 53; 54; 55; 56; 57; 58; 59; 60; 61; 62; 63; 64; 65; 66; 67; 68; 69; 70; 71; 72; 73; 74; 75; 76; 77; 78; 79; 80; 81; 82; 83; 84; 85; 86; 87; 88; 89; 90; 91; 92; 93; 94; 95; 96; 97; 98; 99; 100; ...]</code> - note the … at the end, which indicate that there is more.</p> </blockquote> <p>What if you inadvertently started a very long computation, or an infinite loop? In Visual Studio, you can either kill the session entirely, by right-clicking over the FSI window and selecting “Reset Interactive Session” or Ctrl + Alt + R, or cancel the latest evaluation you requested (“Cancel Interactive Evaluation”, or Ctrl + Break.).</p> -<h2 id="Tip-3-Run-Scripts-from-the-Command-Line"><a href="#Tip-3-Run-Scripts-from-the-Command-Line" class="headerlink" title="Tip 3: Run Scripts from the Command Line"></a>Tip 3: Run Scripts from the Command Line</h2><p>Besides interactive scripting, you can also run a script from the command line, by using <code>FSI.exe</code>:</p> +<h2 id="Tip-3-Run-Scripts-from-the-Command-Line"><a class="header-anchor" href="#Tip-3-Run-Scripts-from-the-Command-Line">¶</a>Tip 3: Run Scripts from the Command Line</h2> +<p>Besides interactive scripting, you can also run a script from the command line, by using <code>FSI.exe</code>:</p> <p><code>>fsi.exe "C:\myscript.fsx"</code></p> <blockquote> -<p><code>FSI.exe</code> is typically located at <code>C:\Program Files (x86)\Microsoft SDKs\F#\4.0\Framework\v4.0</code>. You can also install it separately, see <a href="http://fsharp.org/">fsharp.org/use</a> section for instructions for various platforms.</p> +<p><code>FSI.exe</code> is typically located at <code>C:\Program Files (x86)\Microsoft SDKs\F#\4.0\Framework\v4.0</code>. You can also install it separately, see <a href="http://fsharp.org/">fsharp.org/use</a> section for instructions for various platforms.</p> </blockquote> <p>You can define different behaviors in your script, depending on whether it is run interactively or from the command line, like this:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">#if INTERACTIVE</span><br><span class="line">let msg = "Interactive"</span><br><span class="line">#else</span><br><span class="line">let msg = "Not Interactive"</span><br><span class="line">#endif</span><br><span class="line"></span><br><span class="line">printfn "%s" msg</span><br></pre></td></tr></table></figure> - <p><em>Updated, Sep 19: thanks Matt Klein for <a href="http://stackoverflow.com/q/39581342/114519">pointing the issue</a>.</em></p> <p>For more information on FSI from the command line, <a href="https://msdn.microsoft.com/en-us/library/dd233175.aspx">check the reference page here</a>.</p> <p><em>Updated, Feb 20: <a href="https://twitter.com/genTauro42">Ramon Soto Mathiesen</a> points out that <a href="https://twitter.com/genTauro42/status/696407757835132928">Tip 9 also applies to the command line</a>.</em></p> -<h2 id="Tip-4-Use-Relative-Paths"><a href="#Tip-4-Use-Relative-Paths" class="headerlink" title="Tip 4: Use Relative Paths"></a>Tip 4: Use Relative Paths</h2><p>Sometimes, your script will reference another resource; for instance, you need to read the contents of a <code>.txt</code> file somewhere. You can use absolute path, as in:</p> +<h2 id="Tip-4-Use-Relative-Paths"><a class="header-anchor" href="#Tip-4-Use-Relative-Paths">¶</a>Tip 4: Use Relative Paths</h2> +<p>Sometimes, your script will reference another resource; for instance, you need to read the contents of a <code>.txt</code> file somewhere. You can use absolute path, as in:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">File.ReadAllLines @"C:/data/myfile.txt"</span><br></pre></td></tr></table></figure> - <blockquote> <p>Pre-pending a string with <code>@</code> makes it a verbatim string, and ignore escape sequences, such as <code>\</code>.</p> </blockquote> @@ -65,28 +64,22 @@ <p>However, if that resource lives in a location relative to your script, consider using relative path, so that you can move your script folder around without breaking it.</p> <p>Relative paths can be a bit tricky; for instance, running the following code interactively…</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">System.Environment.CurrentDirectory</span><br></pre></td></tr></table></figure> - <p>… produces a potentially unexpected result in FSI:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">val it : string = "C:\Users\Mathias Brandewinder\AppData\Local\Temp"</span><br><span class="line">></span><br></pre></td></tr></table></figure> - <p>You can avoid these issues by using built-in constants, which refer respectively to the directory where the script lives, the script file name, and the current line of the script:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">__SOURCE_DIRECTORY__</span><br><span class="line">__SOURCE_FILE__</span><br><span class="line">__LINE__</span><br></pre></td></tr></table></figure> - <p>So if your folder structure was along these lines…</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">root</span><br><span class="line"> /src/script.fsx</span><br><span class="line"> /data/data.txt</span><br></pre></td></tr></table></figure> - <p>… you could refer to the data file <code>data.txt</code> from your script like this:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">let path = System.IO.Path.Combine(__SOURCE_DIRECTORY__,"..","data/data.txt")</span><br><span class="line">System.IO.File.ReadAllText path</span><br></pre></td></tr></table></figure> - -<h2 id="Tip-5-Including-Assemblies"><a href="#Tip-5-Including-Assemblies" class="headerlink" title="Tip 5: Including Assemblies"></a>Tip 5: Including Assemblies</h2><p>By default, FSI loads <code>FSharp.Core</code> and nothing else. If you want to use <code>System.DateTime</code>, you will need to first <code>open System</code> in your script. If you want to use an assembly that is not part of the standard .NET distribution, you will need to reference it first using <code>#r</code>. Imagine for instance that you installed the Nuget package <code>fsharp.data</code>; to use it in your script, you would do something like:</p> +<h2 id="Tip-5-Including-Assemblies"><a class="header-anchor" href="#Tip-5-Including-Assemblies">¶</a>Tip 5: Including Assemblies</h2> +<p>By default, FSI loads <code>FSharp.Core</code> and nothing else. If you want to use <code>System.DateTime</code>, you will need to first <code>open System</code> in your script. If you want to use an assembly that is not part of the standard .NET distribution, you will need to reference it first using <code>#r</code>. Imagine for instance that you installed the Nuget package <code>fsharp.data</code>; to use it in your script, you would do something like:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">#r @"../packages/FSharp.Data.2.2.5/lib/net40/FSharp.Data.dll"</span><br><span class="line">open FSharp.Data</span><br></pre></td></tr></table></figure> - <blockquote> <p>When you execute <code>open System</code> in interactive, don’t worry if nothing seems to happen: the only result is a new <code>></code> showing up in FSI.</p> </blockquote> <p>For assemblies that are part of .NET but not referenced by default, you can use a shorter version:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">#r @"System.Xaml"</span><br><span class="line">open System.Xaml</span><br></pre></td></tr></table></figure> - <blockquote> <p>In Visual Studio, you can right-click a reference from Solution Explorer, and send to F# interactive. You can then directly open it, and start using it in FSI.</p> </blockquote> @@ -100,48 +93,47 @@ <p><a href="https://twitter.com/jeroldhaas">@jeroldhaas</a> <a href="https://twitter.com/sergey_tihon">@sergey_tihon</a> <a href="https://twitter.com/brandewinder">@brandewinder</a> Use <a href="https://twitter.com/hashtag/I?src=hash">#I</a> <strong>SOURCE_DIRECTORY</strong>, it is wondrous, very satisfying. All relative paths then work</p> <p>— Don Syme (@dsyme) <a href="https://twitter.com/dsyme/status/696429115184955393">February 7, 2016</a></p> </blockquote> -<h2 id="Tip-6-Use-Paket"><a href="#Tip-6-Use-Paket" class="headerlink" title="Tip 6: Use Paket"></a>Tip 6: Use <code>Paket</code></h2><p>The Nuget package manager is useful to consume existing packages. However, by default, Nuget stores assemblies in a folder that includes the package version number. This is very impractical for a script. In our example above, if <code>fsharp.data</code> gets an update, our script reference will be broken once we update the Nuget package:</p> +<h2 id="Tip-6-Use-Paket"><a class="header-anchor" href="#Tip-6-Use-Paket">¶</a>Tip 6: Use <code>Paket</code></h2> +<p>The Nuget package manager is useful to consume existing packages. However, by default, Nuget stores assemblies in a folder that includes the package version number. This is very impractical for a script. In our example above, if <code>fsharp.data</code> gets an update, our script reference will be broken once we update the Nuget package:</p> <p><code>#r @"../packages/FSharp.Data.2.2.5/lib/net40/FSharp.Data.dll"</code></p> <p>Fixing the script requires manually editing the version number in the path, which quickly becomes a pain. <a href="https://fsprojects.github.io/Paket/">Paket</a> provides a better experience, because it stores packages without the version number, in this case, under:</p> <p><code>#r @"../packages/FSharp.Data/lib/net40/FSharp.Data.dll"</code></p> <p>Your scripts will now gracefully handle version number changes.</p> <p>If you end up consuming numerous packages, you can make your life even easier, by referencing paths where assemblies might be searched for, using <code>#I</code>:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">#I @"../packages/</span><br><span class="line">#r @"FSharp.Data/lib/net40/FSharp.Data.dll"</span><br></pre></td></tr></table></figure> - <blockquote> <p>If your primary goal is to “just script”, consider using <a href="https://atom.io/">Atom</a> or <a href="https://code.visualstudio.com/">VSCode</a>, with the <a href="http://ionide.io/">Ionide plugin</a>. You can create and run free-standing F# scripts, with beautiful <a href="http://ionide.io/#paket-integration">Paket integration</a>.</p> </blockquote> -<h2 id="Tip-7-Include-Files"><a href="#Tip-7-Include-Files" class="headerlink" title="Tip 7: Include Files"></a>Tip 7: Include Files</h2><p>You might want to use the code from an existing file in your script. Suppose that we have a code file <code>Code.fs</code> somewhere, looking like this:</p> +<h2 id="Tip-7-Include-Files"><a class="header-anchor" href="#Tip-7-Include-Files">¶</a>Tip 7: Include Files</h2> +<p>You might want to use the code from an existing file in your script. Suppose that we have a code file <code>Code.fs</code> somewhere, looking like this:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">namespace Mathias</span><br><span class="line"></span><br><span class="line">module Common =</span><br><span class="line"> let hello name = sprintf "Hello, %s" name</span><br></pre></td></tr></table></figure> - <p>You can use that code from your script, by using the <code>#load</code> directive:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">#load "Code.fs"</span><br><span class="line">open Mathias.Common</span><br><span class="line">hello "World"</span><br></pre></td></tr></table></figure> - <blockquote> <p>You might have to close and re-open the script file if you end up changing the contents of the file.</p> </blockquote> <blockquote> <p>If the file you are attempting to load contains references to other assemblies or files, you might get an error on the <code>#load</code> statement: “One or more errors in loaded files. The namespace or module … is not defined”. Simply reference the missing assemblies above the <code>#load</code> statement, so that your script uses the same dependencies as the file it refers to.</p> </blockquote> -<h2 id="Tip-8-Profile-your-Code-with-time"><a href="#Tip-8-Profile-your-Code-with-time" class="headerlink" title="Tip 8: Profile your Code with #time"></a>Tip 8: Profile your Code with #time</h2><p>Another handy directive, <code>#time</code>, turns on basic profiling. Once it is executed, for every block of code you send for execution you will see timing and garbage collection information. For instance, running this code…</p> +<h2 id="Tip-8-Profile-your-Code-with-time"><a class="header-anchor" href="#Tip-8-Profile-your-Code-with-time">¶</a>Tip 8: Profile your Code with #time</h2> +<p>Another handy directive, <code>#time</code>, turns on basic profiling. Once it is executed, for every block of code you send for execution you will see timing and garbage collection information. For instance, running this code…</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">#time</span><br><span class="line">[| 1 .. 10000000 |] |> Array.map (fun x -> x * x)</span><br></pre></td></tr></table></figure> - <p>… will produce the following in FSI:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">--> Timing now on</span><br><span class="line"></span><br><span class="line">Real: 00:00:00.887, CPU: 00:00:00.828, GC gen0: 2, gen1: 2, gen2: 2</span><br><span class="line">val it : int [] =</span><br><span class="line"> [|1; 4; 9; 16; 25; 36; 49; // snipped for brevity</span><br></pre></td></tr></table></figure> - <p>We get the wall time and CPU time it took, as well as some information about garbage collection in generations 0, 1 and 2. This would not replace a full-blown profiler, but this is an awfully convenient tool to figure out quickly if there are obvious ways to improve a piece of code.</p> <p>Note that every time you execute <code>#time</code>, the timer will be switched from on to off, or vice-versa. This is not always convenient; you can also explicitly set it to the desired state, like this:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">#time "on"</span><br><span class="line">// everything now is timed</span><br><span class="line">#time "off"</span><br></pre></td></tr></table></figure> - <blockquote> <p>If you are interested in profiling, you should take a look at <a href="http://www.privateeye.io/">PrivateEye</a>; check out <a href="https://twitter.com/gregyoung">Greg Young</a>’s <a href="https://vimeo.com/131637366">talk at NDC Oslo 2015</a> to get a feel for what it does.</p> </blockquote> -<h2 id="Tip-9-Turn-64-bits-on"><a href="#Tip-9-Turn-64-bits-on" class="headerlink" title="Tip 9: Turn 64-bits on"></a>Tip 9: Turn 64-bits on</h2><p>Hat tip to <a href="https://twitter.com/rickasaurus">Rick Minerich</a> for that one. I’ll refer you to his blog post to see how to <a href="http://richardminerich.com/2013/03/setting-up-fsharp-interactive-for-machine-learning-with-large-datasets/">set FSI to 64 bits to handle large datasets</a>.</p> -<h2 id="Tip-10-Bonus-Material"><a href="#Tip-10-Bonus-Material" class="headerlink" title="Tip 10: Bonus Material"></a>Tip 10: Bonus Material</h2><p>Did you know that you could…</p> +<h2 id="Tip-9-Turn-64-bits-on"><a class="header-anchor" href="#Tip-9-Turn-64-bits-on">¶</a>Tip 9: Turn 64-bits on</h2> +<p>Hat tip to <a href="https://twitter.com/rickasaurus">Rick Minerich</a> for that one. I’ll refer you to his blog post to see how to <a href="http://richardminerich.com/2013/03/setting-up-fsharp-interactive-for-machine-learning-with-large-datasets/">set FSI to 64 bits to handle large datasets</a>.</p> +<h2 id="Tip-10-Bonus-Material"><a class="header-anchor" href="#Tip-10-Bonus-Material">¶</a>Tip 10: Bonus Material</h2> +<p>Did you know that you could…</p> <ul> <li><a href="https://channel9.msdn.com/Events/Visual-Studio/Visual-Studio-2015-Final-Release-Event/Six-Quick-Picks-from-Visual-F-40">debug an F# script? (around 0:12:35 in)</a></li> <li><a href="http://www.swensensoftware.com/fseye">inspect the objects in your FSI session with FsEye?</a></li> -<li>change the FSI font size in Tools/Options/Environment/Fonts and Colors/Show Settings for/F# Interactive?</li> +<li>change the FSI font size in Tools/Options/Environment/Fonts and Colors/Show Settings for/F# Interactive?</li> <li>add your own pretty-printer to FSI, <a href="https://github.com/mathnet/mathnet-numerics/blob/master/src/FSharp/MathNet.Numerics.fsx">like this</a>?</li> <li>mess with your coworkers’ mental sanity, by executing <code>(*</code> (opening a multiline comment) in FSI? (credit: <a href="https://twitter.com/tomaspetricek">Tomas</a>)</li> <li>simplify loading references with Visual Studio and Power Tools? (credit: <a href="https://twitter.com/kitlovesfsharp">Kit Eason</a>, see details in comments section).</li> @@ -161,14 +153,20 @@ <entry> <title>A Brief History of Just-In-Time</title> <url>/2023/09/28/A-Brief-History-of-Just-In-Time/</url> - <content><![CDATA[<p>Software systems have been using “just-in-time” compilation (JIT) techniques since the<br>1960s. Broadly, JIT compilation includes any translation performed dynamically, after a<br>program has started execution. We examine the motivation behind JIT compilation and<br>constraints imposed on JIT compilation systems, and present a classification scheme for<br>such systems. This classification emerges as we survey forty years of JIT work, from<br>1960–2000.</p> + <content><![CDATA[<p>Software systems have been using “just-in-time” compilation (JIT) techniques since the<br> +1960s. Broadly, JIT compilation includes any translation performed dynamically, after a<br> +program has started execution. We examine the motivation behind JIT compilation and<br> +constraints imposed on JIT compilation systems, and present a classification scheme for<br> +such systems. This classification emerges as we survey forty years of JIT work, from<br> +1960–2000.</p> <ul> <li><a href="/papers/A%20Brief%20History%20of%20Just-In-Time.pdf">论文链接</a></li> </ul> <p>主要介绍了JIT的历史和发展过程, 从上世纪六十年代开始, 一直到现在的第四代JIT系统, 大概有三点:</p> <ul> <li>介绍了JIT每一代出现的动机和约束条件</li> -<li>介绍了对各种JIT技术的分类方式<blockquote> +<li>介绍了对各种JIT技术的分类方式 +<blockquote> <ol> <li>Invocation</li> <li>Executability</li> @@ -198,7 +196,8 @@ <ul> <li><a href="/papers/Approach%20to%20Idiopathic%20Anaphylaxis%20in%20Adolescents.pdf">原始文章</a></li> </ul> -<h2 id="其他"><a href="#其他" class="headerlink" title="其他"></a>其他</h2><p>端坐呼吸或端坐呼吸是平躺时发生的呼吸短促,导致患者不得不支撑在床上或坐在椅子上睡觉。它通常被视为心力衰竭的晚期表现,是由于液体重新分布到中央循环,导致肺毛细血管压力增加并导致呼吸困难所致。它也见于腹部肥胖或肺部疾病的情况。端坐呼吸与平呼吸相反,平呼吸是指坐或站直时呼吸急促会加重。</p> +<h2 id="其他"><a class="header-anchor" href="#其他">¶</a>其他</h2> +<p>端坐呼吸或端坐呼吸是平躺时发生的呼吸短促,导致患者不得不支撑在床上或坐在椅子上睡觉。它通常被视为心力衰竭的晚期表现,是由于液体重新分布到中央循环,导致肺毛细血管压力增加并导致呼吸困难所致。它也见于腹部肥胖或肺部疾病的情况。端坐呼吸与平呼吸相反,平呼吸是指坐或站直时呼吸急促会加重。</p> ]]></content> <tags> <tag>Medicine</tag> @@ -209,21 +208,26 @@ <url>/2024/09/15/Advanced-C-binding-using-ocaml-ctypes-and-dune/</url> <content><</code> C API.</p> <p>I had already decided to use the very elegant <code>[ocaml-ctypes](https://github.com/ocamllabs/ocaml-ctypes)</code> module for the SRT binding so I went with it and created a <code>[ocaml-sys-socket](https://github.com/toots/ocaml-sys-socket)</code> module using it as well. It was a very interesting experience that I would like to describe here!</p> -<h1 id="ocaml-ctypes"><a href="#ocaml-ctypes" class="headerlink" title="ocaml-ctypes"></a>ocaml-ctypes</h1><p>The idea behind OCaml ctypes is to create a binding against a C library without having to write C code, or as least as possible. The most straight-forward way of using it is via <code>[libffi](https://github.com/libffi/libffi)</code> , providing access to dynamically-loaded libraries.</p> +<h1>ocaml-ctypes</h1> +<p>The idea behind OCaml ctypes is to create a binding against a C library without having to write C code, or as least as possible. The most straight-forward way of using it is via <code>[libffi](https://github.com/libffi/libffi)</code> , providing access to dynamically-loaded libraries.</p> <p>The second way of using it is by letting the module generate the basic C stubs required to build and link against a shared library. This is the mode that we’re going to use here. In this mode, the programmer has to describe the C headers of the library they intent to bind to using dedicated OCaml modules, operators and types. From that description, ocaml-ctypes is able to generate the required glue for the binding.</p> <p>One advantage of using ocaml-ctypes is that the created bindings make as few assumptions as possible about the <a href="https://caml.inria.fr/pub/docs/manual-ocaml/intfc.html">OCaml C interfacing API</a>. This is pretty nice, in particular since the <a href="https://github.com/ocaml/ocaml">OCaml compiler</a> is moving pretty quickly these days (which is awesome!) and also if, perhaps one day, <a href="https://github.com/ocaml-multicore/ocaml-multicore">support for multi-core</a> is added to the compiler, which will undoubtedly change the C interface API quite a bit.</p> -<h1 id="dune"><a href="#dune" class="headerlink" title="dune"></a>dune</h1><p><code>[dune](https://github.com/ocaml/dune)</code> (formally <code>jbuilder</code> ) is a build system for OCaml projects that has recently raised to much popularity, particularly due to its tight integration with the rest of the OCaml ecosystem, such as <code>[ocamlfind](http://projects.camlcity.org/projects/findlib.html)</code> and <code>[opam](https://opam.ocaml.org/)</code> .</p> +<h1>dune</h1> +<p><code>[dune](https://github.com/ocaml/dune)</code> (formally <code>jbuilder</code> ) is a build system for OCaml projects that has recently raised to much popularity, particularly due to its tight integration with the rest of the OCaml ecosystem, such as <code>[ocamlfind](http://projects.camlcity.org/projects/findlib.html)</code> and <code>[opam](https://opam.ocaml.org/)</code> .</p> <p>My personal motto in programming in general is that <em>“Simple things should be simple, but complex things should be possible”</em>. <code>dune</code> certainly does not fit into that category but, rather, makes some complex things extremely easy to setup. It’s the kind of tool that will make your life incredibly easier when what you intent to do fits well within their workflow but might not be easy to bend to some very specific niche use. We will see one such case below.</p> <p>At any rate, it’s been an amazing experience getting to learn how to use <code>dune</code> and the resulting code and build system is remarkably short and elegant, yet very powerful.</p> -<h1 id="socket-h"><a href="#socket-h" class="headerlink" title="socket.h"></a>socket.h</h1><p><code>socket.h</code> is the Unix header that describes the C API to various socket operations, IP version 4 and 6 as well as unix file sockets. There is also a windows API mimicking it, which makes most code using it easily portable to windows.</p> +<h1>socket.h</h1> +<p><code>socket.h</code> is the Unix header that describes the C API to various socket operations, IP version 4 and 6 as well as unix file sockets. There is also a windows API mimicking it, which makes most code using it easily portable to windows.</p> <p>Most network-based C libraries refer to <code>socket.h</code> to describe the type of socket that can be used with their API so it’s an important entry point for a lot of network operations and one that would be nice to support as generically as possible in OCaml.</p> <p>The catch, though, is that, most likely for historical reasons¹, the <a href="https://pubs.opengroup.org/onlinepubs/7908799/xns/syssocket.h.html">POSIX specifications</a> only <em>partially</em> defines some of the required data structures and types, which makes it possible to write C code using them but does not give enough information to write C bindings without having to use the compiler to parse the actual system-specific headers of the running host.</p> <p>For instance, here’s how the <code>sockaddr</code> structure is specified:</p> -<p>The <em><sys/socket.h></em> header defines the sockaddr structure that includes at least the following members:sa_family_t sa_family address family<br>char sa_data[] socket address (variable-length data)</p> +<p>The <em><sys/socket.h></em> header defines the sockaddr structure that includes at least the following members:sa_family_t sa_family address family<br> +char sa_data[] socket address (variable-length data)</p> <p>Likewise, here’s what is specified about the size of the <code>socklen_t</code> data type:</p> -<p><em><sys/socket.h></em> makes available a type, socklen_t, which is an unsigned opaque integral type of length of at least 32 bits.</p> +<p><em><sys/socket.h></em> makes available a type, socklen_t, which is an unsigned opaque integral type of length of at least 32 bits.</p> <p>Thus, in order to know the exact offset of <code>sa_family</code> inside the <code>sockaddr</code> structure or the actual size of a <code>socklen_t</code> integer, one has to include the OS-specific header, parse its definitions for that specific OS and, only then, is it possible to compute that offset or data size. Let’s see how it’s done in our binding now!</p> -<h1 id="Putting-it-together"><a href="#Putting-it-together" class="headerlink" title="Putting it together"></a>Putting it together</h1><p>The C binding requires 4 separate passes:</p> +<h1>Putting it together</h1> +<p>The C binding requires 4 separate passes:</p> <ul> <li>The <code>[constants](https://github.com/toots/ocaml-sys-socket/tree/master/src/sys-socket/constants)</code> pass, which computes and exports some specific constant and data sizes, computed from the C headers</li> <li>The <code>[types](https://github.com/toots/ocaml-sys-socket/tree/master/src/sys-socket/types)</code> pass, which, given the system-specific constants and sizes exported in the previous phase, defines the actual C data structure bindings.</li> @@ -231,73 +235,62 @@ <li>Finally, the <a href="https://github.com/toots/ocaml-sys-socket/blob/master/src/sys-socket/sys_socket.mli">last pass</a> does a cleanup of the <code>stubs</code> pass to export a relevant and OCaml- (and <code>ocaml-ctypes</code>) specific public API that is to be used by users of the module.</li> </ul> <p><code>dune</code> makes each of these steps fairly easy to integrate into the next one, defining compilation elements and binaries to build before moving to the next pass.</p> -<h2 id="Constants-pass"><a href="#Constants-pass" class="headerlink" title="Constants pass"></a>Constants pass</h2><p>During that pass, we compute and export all required C values defined in the headers. We also add our own constants, which give us the sizes that the POSIX specifications leave up to the OS. Here’s the OCaml code for it:</p> +<h2 id="Constants-pass"><a class="header-anchor" href="#Constants-pass">¶</a>Constants pass</h2> +<p>During that pass, we compute and export all required C values defined in the headers. We also add our own constants, which give us the sizes that the POSIX specifications leave up to the OS. Here’s the OCaml code for it:</p> <figure class="highlight ocaml"><table><tr><td class="code"><pre><span class="line"><span class="keyword">module</span> <span class="type">Def</span> (<span class="type">S</span> : <span class="type">Cstubs</span>.<span class="type">Types</span>.<span class="type">TYPE</span>) = <span class="keyword">struct</span></span><br><span class="line"> <span class="keyword">let</span> af_inet = <span class="type">S</span>.constant <span class="string">"AF_INET"</span> <span class="type">S</span>.<span class="built_in">int</span></span><br><span class="line"> <span class="keyword">let</span> af_inet6 = <span class="type">S</span>.constant <span class="string">"AF_INET6"</span> <span class="type">S</span>.<span class="built_in">int</span></span><br><span class="line"> <span class="keyword">let</span> af_unix = <span class="type">S</span>.constant <span class="string">"AF_UNIX"</span> <span class="type">S</span>.<span class="built_in">int</span></span><br><span class="line"> <span class="keyword">let</span> af_unspec = <span class="type">S</span>.constant <span class="string">"AF_UNSPEC"</span> <span class="type">S</span>.<span class="built_in">int</span></span><br><span class="line"> <span class="keyword">let</span> sa_data_len = <span class="type">S</span>.constant <span class="string">"SA_DATA_LEN"</span> <span class="type">S</span>.<span class="built_in">int</span></span><br><span class="line"> <span class="keyword">let</span> sa_family_len = <span class="type">S</span>.constant <span class="string">"SA_FAMILY_LEN"</span> <span class="type">S</span>.<span class="built_in">int</span></span><br><span class="line"> <span class="keyword">let</span> sock_dgram = <span class="type">S</span>.constant <span class="string">"SOCK_DGRAM"</span> <span class="type">S</span>.<span class="built_in">int</span></span><br><span class="line"> <span class="keyword">let</span> sock_stream = <span class="type">S</span>.constant <span class="string">"SOCK_STREAM"</span> <span class="type">S</span>.<span class="built_in">int</span></span><br><span class="line"> <span class="keyword">let</span> sock_seqpacket = <span class="type">S</span>.constant <span class="string">"SOCK_STREAM"</span> <span class="type">S</span>.<span class="built_in">int</span></span><br><span class="line"> <span class="keyword">let</span> socklen_t_len = <span class="type">S</span>.constant <span class="string">"SOCKLEN_T_LEN"</span> <span class="type">S</span>.<span class="built_in">int</span></span><br><span class="line"> <span class="keyword">let</span> ni_maxserv = <span class="type">S</span>.constant <span class="string">"NI_MAXSERV"</span> <span class="type">S</span>.<span class="built_in">int</span></span><br><span class="line"> <span class="keyword">let</span> ni_maxhost = <span class="type">S</span>.constant <span class="string">"NI_MAXHOST"</span> <span class="type">S</span>.<span class="built_in">int</span></span><br><span class="line"> <span class="keyword">let</span> ni_numerichost = <span class="type">S</span>.constant <span class="string">"NI_NUMERICHOST"</span> <span class="type">S</span>.<span class="built_in">int</span></span><br><span class="line"> <span class="keyword">let</span> ni_numericserv = <span class="type">S</span>.constant <span class="string">"NI_NUMERICSERV"</span> <span class="type">S</span>.<span class="built_in">int</span></span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure> - <p>Pretty straightforward! Some of these constants are defined by the POSIX headers and some are custom defined for our needs, for instance <code>SOCKLEN_T_LEN</code> . Here’s how they are extracted, using the <code>dune</code> build configuration for <code>[gen_constants_c](https://github.com/toots/ocaml-sys-socket/blob/master/src/sys-socket/generator/gen_constants_c.ml)</code>:</p> <figure class="highlight ocaml"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> c_headers = <span class="string">"</span></span><br><span class="line"><span class="string">#ifdef _WIN32</span></span><br><span class="line"><span class="string"> #include <winsock2.h></span></span><br><span class="line"><span class="string"> #include <ws2tcpip.h></span></span><br><span class="line"><span class="string">#else</span></span><br><span class="line"><span class="string"> #include <sys/socket.h></span></span><br><span class="line"><span class="string"> #include <sys/un.h></span></span><br><span class="line"><span class="string"> #include <netdb.h></span></span><br><span class="line"><span class="string">#endif</span></span><br><span class="line"><span class="string">#define SA_DATA_LEN (sizeof(((struct sockaddr*)0)->sa_data))</span></span><br><span class="line"><span class="string">#define SA_FAMILY_LEN (sizeof(((struct sockaddr*)0)->sa_family))</span></span><br><span class="line"><span class="string">#define SOCKLEN_T_LEN (sizeof(socklen_t))</span></span><br><span class="line"><span class="string">#ifndef NI_MAXHOST</span></span><br><span class="line"><span class="string"> #define NI_MAXHOST 1025</span></span><br><span class="line"><span class="string">#endif</span></span><br><span class="line"><span class="string">#ifndef NI_MAXSERV</span></span><br><span class="line"><span class="string"> #define NI_MAXSERV 32</span></span><br><span class="line"><span class="string">#endif</span></span><br><span class="line"><span class="string">"</span></span><br><span class="line"><span class="keyword">let</span> <span class="literal">()</span> =</span><br><span class="line"> <span class="keyword">let</span> fname = <span class="type">Sys</span>.argv.(<span class="number">1</span>) <span class="keyword">in</span></span><br><span class="line"> <span class="keyword">let</span> oc = open_out_bin fname <span class="keyword">in</span></span><br><span class="line"> <span class="keyword">let</span> format =</span><br><span class="line"> <span class="type">Format</span>.formatter_of_out_channel oc</span><br><span class="line"> <span class="keyword">in</span></span><br><span class="line"> <span class="type">Format</span>.fprintf format <span class="string">"%s@\n"</span> c_headers;</span><br><span class="line"> <span class="type">Cstubs</span>.<span class="type">Types</span>.write_c format (<span class="keyword">module</span> <span class="type">Sys_socket_constants</span>.<span class="type">Def</span>);</span><br><span class="line"> <span class="type">Format</span>.pp_print_flush format <span class="literal">()</span>;</span><br><span class="line"> close_out oc</span><br></pre></td></tr></table></figure> - <p>This OCaml code makes use of <code>ocaml-ctypes</code> to build a binary that exports the OCaml interface defined by <code>Sys_socket_constants.Def</code> . Once compiled, its output looks like this:</p> <figure class="highlight ocaml"><table><tr><td class="code"><pre><span class="line"><span class="keyword">include</span> <span class="type">Ctypes</span></span><br><span class="line"><span class="keyword">let</span> lift x = x</span><br><span class="line"><span class="keyword">open</span> <span class="type">Ctypes_static</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> <span class="keyword">rec</span> field : <span class="keyword">type</span> t a. t typ -> <span class="built_in">string</span> -> a typ -> (a, t) field =</span><br><span class="line"> <span class="keyword">fun</span> s fname ftype -> <span class="keyword">match</span> s, fname <span class="keyword">with</span></span><br><span class="line"> | <span class="type">View</span> { ty }, _ -></span><br><span class="line"> <span class="keyword">let</span> { ftype; foffset; fname } = field ty fname ftype <span class="keyword">in</span></span><br><span class="line"> { ftype; foffset; fname }</span><br><span class="line"> | _ -> failwith (<span class="string">"Unexpected field "</span>^ fname)</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> <span class="keyword">rec</span> seal : <span class="keyword">type</span> a. a typ -> <span class="built_in">unit</span> = <span class="keyword">function</span></span><br><span class="line"> | <span class="type">Struct</span> { tag; spec = <span class="type">Complete</span> _ } -></span><br><span class="line"> raise (<span class="type">ModifyingSealedType</span> tag)</span><br><span class="line"> | <span class="type">Union</span> { utag; uspec = <span class="type">Some</span> _ } -></span><br><span class="line"> raise (<span class="type">ModifyingSealedType</span> utag)</span><br><span class="line"> | <span class="type">View</span> { ty } -> seal ty</span><br><span class="line"> | _ -></span><br><span class="line"> raise (<span class="type">Unsupported</span> <span class="string">"Sealing a non-structured type"</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> <span class="symbol">'a</span> const = <span class="symbol">'a</span></span><br><span class="line"><span class="keyword">let</span> constant (<span class="keyword">type</span> t) name (t : t typ) : t = <span class="keyword">match</span> t, name <span class="keyword">with</span></span><br><span class="line"> | <span class="type">Ctypes_static</span>.<span class="type">Primitive</span> <span class="type">Cstubs_internals</span>.<span class="type">Int</span>, <span class="string">"NI_NUMERICSERV"</span> -></span><br><span class="line"> <span class="number">8</span></span><br><span class="line"> | <span class="type">Ctypes_static</span>.<span class="type">Primitive</span> <span class="type">Cstubs_internals</span>.<span class="type">Int</span>, <span class="string">"NI_NUMERICHOST"</span> -></span><br><span class="line"> <span class="number">2</span></span><br><span class="line"> | <span class="type">Ctypes_static</span>.<span class="type">Primitive</span> <span class="type">Cstubs_internals</span>.<span class="type">Int</span>, <span class="string">"NI_MAXHOST"</span> -></span><br><span class="line"> <span class="number">1025</span></span><br><span class="line"> | <span class="type">Ctypes_static</span>.<span class="type">Primitive</span> <span class="type">Cstubs_internals</span>.<span class="type">Int</span>, <span class="string">"NI_MAXSERV"</span> -></span><br><span class="line"> <span class="number">32</span></span><br><span class="line"> | <span class="type">Ctypes_static</span>.<span class="type">Primitive</span> <span class="type">Cstubs_internals</span>.<span class="type">Int</span>, <span class="string">"SOCKLEN_T_LEN"</span> -></span><br><span class="line"> <span class="number">4</span></span><br><span class="line"> | <span class="type">Ctypes_static</span>.<span class="type">Primitive</span> <span class="type">Cstubs_internals</span>.<span class="type">Int</span>, <span class="string">"SOCK_STREAM"</span> -></span><br><span class="line"> <span class="number">1</span></span><br><span class="line"> | <span class="type">Ctypes_static</span>.<span class="type">Primitive</span> <span class="type">Cstubs_internals</span>.<span class="type">Int</span>, <span class="string">"SOCK_STREAM"</span> -></span><br><span class="line"> <span class="number">1</span></span><br><span class="line"> | <span class="type">Ctypes_static</span>.<span class="type">Primitive</span> <span class="type">Cstubs_internals</span>.<span class="type">Int</span>, <span class="string">"SOCK_DGRAM"</span> -></span><br><span class="line"> <span class="number">2</span></span><br><span class="line"> | <span class="type">Ctypes_static</span>.<span class="type">Primitive</span> <span class="type">Cstubs_internals</span>.<span class="type">Int</span>, <span class="string">"SA_FAMILY_LEN"</span> -></span><br><span class="line"> <span class="number">1</span></span><br><span class="line"> | <span class="type">Ctypes_static</span>.<span class="type">Primitive</span> <span class="type">Cstubs_internals</span>.<span class="type">Int</span>, <span class="string">"SA_DATA_LEN"</span> -></span><br><span class="line"> <span class="number">14</span></span><br><span class="line"> | <span class="type">Ctypes_static</span>.<span class="type">Primitive</span> <span class="type">Cstubs_internals</span>.<span class="type">Int</span>, <span class="string">"AF_UNSPEC"</span> -></span><br><span class="line"> <span class="number">0</span></span><br><span class="line"> | <span class="type">Ctypes_static</span>.<span class="type">Primitive</span> <span class="type">Cstubs_internals</span>.<span class="type">Int</span>, <span class="string">"AF_UNIX"</span> -></span><br><span class="line"> <span class="number">1</span></span><br><span class="line"> | <span class="type">Ctypes_static</span>.<span class="type">Primitive</span> <span class="type">Cstubs_internals</span>.<span class="type">Int</span>, <span class="string">"AF_INET6"</span> -></span><br><span class="line"> <span class="number">30</span></span><br><span class="line"> | <span class="type">Ctypes_static</span>.<span class="type">Primitive</span> <span class="type">Cstubs_internals</span>.<span class="type">Int</span>, <span class="string">"AF_INET"</span> -></span><br><span class="line"> <span class="number">2</span></span><br><span class="line"> | _, s -> failwith (<span class="string">"unmatched constant: "</span>^ s)</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> enum (<span class="keyword">type</span> a) name ?typedef ?unexpected (alist : (a * <span class="built_in">int64</span>) <span class="built_in">list</span>) =</span><br><span class="line"> <span class="keyword">match</span> name <span class="keyword">with</span></span><br><span class="line"> | s -></span><br><span class="line"> failwith (<span class="string">"unmatched enum: "</span>^ s)</span><br></pre></td></tr></table></figure> - <p>The files used to describe how to build this binary using <code>dune</code> are located in a separate <code>[generator](https://github.com/toots/ocaml-sys-socket/tree/master/src/sys-socket/generator)</code> directory. Here’s the entry to build this one:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">(executable</span><br><span class="line"> (name gen_constants_c)</span><br><span class="line"> (modules gen_constants_c)</span><br><span class="line"> (libraries sys-socket.constants ctypes.stubs))</span><br><span class="line"></span><br><span class="line">(rule</span><br><span class="line"> (targets gen_constants.c)</span><br><span class="line"> (deps (:gen ./gen_constants_c.exe))</span><br><span class="line"> (action (run %{gen} %{targets})))</span><br><span class="line"></span><br><span class="line">(rule</span><br><span class="line"> (targets gen_constants_c)</span><br><span class="line"> (deps (:c_code ./gen_constants.c))</span><br><span class="line"> (action (run %{ocaml-config:c_compiler} -I %{lib:ctypes:} -I %{ocaml-config:standard_library} -o %{targets} %{c_code})))</span><br></pre></td></tr></table></figure> - <p>This executable is compiled during the next phase. Let’s move into it now!</p> -<h2 id="Types-pass"><a href="#Types-pass" class="headerlink" title="Types pass"></a>Types pass</h2><p>During that phase, we use the constants exported during the previous phase to describe the various C structures and types. This is by far the most complex part of the code, making use of first-class modules and several OCaml tricks.</p> +<h2 id="Types-pass"><a class="header-anchor" href="#Types-pass">¶</a>Types pass</h2> +<p>During that phase, we use the constants exported during the previous phase to describe the various C structures and types. This is by far the most complex part of the code, making use of first-class modules and several OCaml tricks.</p> <p>First, let’s look at how we tell <code>dune</code> that we need to generate the <code>.ml</code> file exporting our required constants from the previous pass:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">(rule</span><br><span class="line"> (targets sys_socket_generated_constants.ml)</span><br><span class="line"> (deps (:exec ../generator/exec.sh)</span><br><span class="line"> (:gen ../generator/gen_constants_c))</span><br><span class="line"> (action (with-stdout-to %{targets}</span><br><span class="line"> (system "%{exec} %{ocaml-config:system} %{gen}"))))</span><br></pre></td></tr></table></figure> - <p>With only this information, if the code refers to a <code>Sys_socket_generated_constants</code> module, <code>dune</code> will know that this module needs to be generated and how to do it. We will explain later the use of the <code>exec.sh</code> wrapper here.</p> <p>Now that we can make use of the exported constants in our OCaml code, let’s see how we define the <code>Socklen</code> module, exporting abstract types and interface to use <code>socklen_t</code> integers:</p> <figure class="highlight ocaml"><table><tr><td class="code"><pre><span class="line"><span class="keyword">module</span> <span class="type">Constants</span> = <span class="type">Sys_socket_constants</span>.<span class="type">Def</span>(<span class="type">Sys_socket_generated_constants</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">module</span> <span class="keyword">type</span> <span class="type">Socklen</span> = <span class="keyword">functor</span> (<span class="type">S</span> : <span class="type">Cstubs</span>.<span class="type">Types</span>.<span class="type">TYPE</span>) -> <span class="keyword">sig</span></span><br><span class="line"> <span class="keyword">type</span> socklen</span><br><span class="line"> <span class="keyword">val</span> socklen_t : socklen <span class="type">S</span>.typ</span><br><span class="line"> <span class="keyword">val</span> int_of_socklen : socklen -> <span class="built_in">int</span></span><br><span class="line"> <span class="keyword">val</span> socklen_of_int : <span class="built_in">int</span> -> socklen</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> socklen : (<span class="keyword">module</span> <span class="type">Socklen</span>) =</span><br><span class="line"> <span class="keyword">match</span> <span class="type">Constants</span>.socklen_t_len <span class="keyword">with</span></span><br><span class="line"> | <span class="number">4</span> -> (<span class="keyword">module</span> <span class="keyword">functor</span> (<span class="type">S</span> : <span class="type">Cstubs</span>.<span class="type">Types</span>.<span class="type">TYPE</span>) -> <span class="keyword">struct</span></span><br><span class="line"> <span class="keyword">type</span> socklen = <span class="type">Unsigned</span>.uint32</span><br><span class="line"> <span class="keyword">let</span> socklen_t = <span class="type">S</span>.uint32_t</span><br><span class="line"> <span class="keyword">let</span> int_of_socklen = <span class="type">Unsigned</span>.<span class="type">UInt32</span>.to_int</span><br><span class="line"> <span class="keyword">let</span> socklen_of_int = <span class="type">Unsigned</span>.<span class="type">UInt32</span>.of_int</span><br><span class="line"> <span class="keyword">end</span>)</span><br><span class="line"> | <span class="number">8</span> -> (<span class="keyword">module</span> <span class="keyword">functor</span> (<span class="type">S</span> : <span class="type">Cstubs</span>.<span class="type">Types</span>.<span class="type">TYPE</span>) -> <span class="keyword">struct</span></span><br><span class="line"> <span class="keyword">type</span> socklen = <span class="type">Unsigned</span>.uint64</span><br><span class="line"> <span class="keyword">let</span> socklen_t = <span class="type">S</span>.uint64_t</span><br><span class="line"> <span class="keyword">let</span> int_of_socklen = <span class="type">Unsigned</span>.<span class="type">UInt64</span>.to_int</span><br><span class="line"> <span class="keyword">let</span> socklen_of_int = <span class="type">Unsigned</span>.<span class="type">UInt64</span>.of_int</span><br><span class="line"> <span class="keyword">end</span>)</span><br><span class="line"> | _ -> <span class="keyword">assert</span> <span class="literal">false</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">module</span> <span class="type">Socklen</span> = (<span class="keyword">val</span> socklen : <span class="type">Socklen</span>)</span><br></pre></td></tr></table></figure> - <p>As you can see, we make use of first-order modules and the size of the <code>socklen_t</code> integer to define the right API for the compiling host. Now let’s see how we define the <code>sockaddr</code> interface:</p> <figure class="highlight ocaml"><table><tr><td class="code"><pre><span class="line"><span class="keyword">module</span> <span class="keyword">type</span> <span class="type">SaFamily</span> = <span class="keyword">sig</span></span><br><span class="line"> <span class="keyword">type</span> sa_family</span><br><span class="line"> <span class="keyword">val</span> int_of_sa_family : sa_family -> <span class="built_in">int</span></span><br><span class="line"> <span class="keyword">val</span> sa_family_of_int : <span class="built_in">int</span> -> sa_family</span><br><span class="line"> </span><br><span class="line"> <span class="keyword">module</span> <span class="type">T</span> : <span class="keyword">functor</span> (<span class="type">S</span> : <span class="type">Cstubs</span>.<span class="type">Types</span>.<span class="type">TYPE</span>) -> <span class="keyword">sig</span></span><br><span class="line"> <span class="keyword">val</span> t : sa_family <span class="type">S</span>.typ</span><br><span class="line"> <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> saFamily : (<span class="keyword">module</span> <span class="type">SaFamily</span>) =</span><br><span class="line"> <span class="keyword">match</span> <span class="type">Constants</span>.sa_family_len <span class="keyword">with</span></span><br><span class="line"> | <span class="number">1</span> -> (<span class="keyword">module</span> <span class="keyword">struct</span></span><br><span class="line"> <span class="keyword">type</span> sa_family = <span class="type">Unsigned</span>.uint8</span><br><span class="line"> <span class="keyword">let</span> int_of_sa_family = <span class="type">Unsigned</span>.<span class="type">UInt8</span>.to_int</span><br><span class="line"> <span class="keyword">let</span> sa_family_of_int = <span class="type">Unsigned</span>.<span class="type">UInt8</span>.of_int </span><br><span class="line"> <span class="keyword">module</span> <span class="type">T</span> (<span class="type">S</span> : <span class="type">Cstubs</span>.<span class="type">Types</span>.<span class="type">TYPE</span>) = <span class="keyword">struct</span></span><br><span class="line"> <span class="keyword">let</span> t = <span class="type">S</span>.uint8_t</span><br><span class="line"> <span class="keyword">end</span></span><br><span class="line"> <span class="keyword">end</span>)</span><br><span class="line">...</span><br><span class="line"></span><br><span class="line"><span class="keyword">module</span> <span class="type">SaFamily</span> = (<span class="keyword">val</span> saFamily : <span class="type">SaFamily</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">module</span> <span class="type">Def</span> (<span class="type">S</span> : <span class="type">Cstubs</span>.<span class="type">Types</span>.<span class="type">TYPE</span>) = <span class="keyword">struct</span></span><br><span class="line"> <span class="keyword">include</span> <span class="type">Constants</span></span><br><span class="line"></span><br><span class="line"> <span class="keyword">include</span> <span class="type">Socklen</span>(<span class="type">S</span>)</span><br><span class="line"></span><br><span class="line"> <span class="keyword">include</span> <span class="type">SaFamily</span></span><br><span class="line"></span><br><span class="line"> <span class="keyword">module</span> <span class="type">SaFamilyT</span> = <span class="type">SaFamily</span>.<span class="type">T</span>(<span class="type">S</span>)</span><br><span class="line"></span><br><span class="line"> <span class="keyword">let</span> sa_family_t = <span class="type">S</span>.typedef <span class="type">SaFamilyT</span>.t <span class="string">"sa_family_t"</span></span><br><span class="line"></span><br><span class="line"> <span class="keyword">module</span> <span class="type">Sockaddr</span> = <span class="keyword">struct</span></span><br><span class="line"> <span class="keyword">type</span> t = <span class="built_in">unit</span></span><br><span class="line"> <span class="keyword">let</span> t = <span class="type">S</span>.structure <span class="string">"sockaddr"</span></span><br><span class="line"> <span class="keyword">let</span> sa_family = <span class="type">S</span>.field t <span class="string">"sa_family"</span> sa_family_t</span><br><span class="line"> <span class="keyword">let</span> sa_data = <span class="type">S</span>.field t <span class="string">"sa_data"</span> (<span class="type">S</span>.<span class="built_in">array</span> sa_data_len <span class="type">S</span>.<span class="built_in">char</span>)</span><br><span class="line"> <span class="keyword">let</span> <span class="literal">()</span> = <span class="type">S</span>.seal t</span><br><span class="line"> <span class="keyword">end</span></span><br><span class="line"> </span><br><span class="line"> ...</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure> - <p>Here, too, we make use of the size of <code>sa_family</code> as exported previously to define the right structure fields.</p> <p>Next step, we need to compile this interface again to export the right offset for the various structures that have been defined. That’s <code>dune</code>’s job again!</p> <p>First, the generator code:</p> <figure class="highlight ocaml"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> c_headers = <span class="string">"</span></span><br><span class="line"><span class="string">#ifdef _WIN32</span></span><br><span class="line"><span class="string"> #include <winsock2.h></span></span><br><span class="line"><span class="string"> #include <ws2tcpip.h></span></span><br><span class="line"><span class="string">#else</span></span><br><span class="line"><span class="string"> #include <sys/socket.h></span></span><br><span class="line"><span class="string"> #include <sys/un.h></span></span><br><span class="line"><span class="string"> #include <netinet/in.h></span></span><br><span class="line"><span class="string"> #include <netdb.h></span></span><br><span class="line"><span class="string">#endif</span></span><br><span class="line"><span class="string">"</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> <span class="literal">()</span> =</span><br><span class="line"> <span class="keyword">let</span> fname = <span class="type">Sys</span>.argv.(<span class="number">1</span>) <span class="keyword">in</span></span><br><span class="line"> <span class="keyword">let</span> oc = open_out_bin fname <span class="keyword">in</span></span><br><span class="line"> <span class="keyword">let</span> format =</span><br><span class="line"> <span class="type">Format</span>.formatter_of_out_channel oc</span><br><span class="line"> <span class="keyword">in</span></span><br><span class="line"> <span class="type">Format</span>.fprintf format <span class="string">"%s@\n"</span> c_headers;</span><br><span class="line"> <span class="type">Cstubs</span>.<span class="type">Types</span>.write_c format (<span class="keyword">module</span> <span class="type">Sys_socket_types</span>.<span class="type">Def</span>);</span><br><span class="line"> <span class="type">Format</span>.pp_print_flush format <span class="literal">()</span>;</span><br><span class="line"> close_out oc</span><br></pre></td></tr></table></figure> - <p>And the build instructions:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">(executable</span><br><span class="line"> (name gen_types_c)</span><br><span class="line"> (modules gen_types_c)</span><br><span class="line"> (libraries sys-socket.types ctypes.stubs))</span><br><span class="line"></span><br><span class="line">(rule</span><br><span class="line"> (targets gen_types.c)</span><br><span class="line"> (deps (:gen ./gen_types_c.exe))</span><br><span class="line"> (action (run %{gen} %{targets})))</span><br><span class="line"></span><br><span class="line">(rule</span><br><span class="line"> (targets gen_types_c)</span><br><span class="line"> (deps (:c_code ./gen_types.c))</span><br><span class="line"> (action (run %{ocaml-config:c_compiler} -I %{lib:ctypes:} -I %{ocaml-config:standard_library} -o %{targets} %{c_code})))</span><br></pre></td></tr></table></figure> - <p>Once, compiled, the exported <code>.ml</code> looks like this:</p> <figure class="highlight ocaml"><table><tr><td class="code"><pre><span class="line"><span class="keyword">include</span> <span class="type">Ctypes</span></span><br><span class="line"><span class="keyword">let</span> lift x = x</span><br><span class="line"><span class="keyword">open</span> <span class="type">Ctypes_static</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> <span class="keyword">rec</span> field : <span class="keyword">type</span> t a. t typ -> <span class="built_in">string</span> -> a typ -> (a, t) field =</span><br><span class="line"> <span class="keyword">fun</span> s fname ftype -> <span class="keyword">match</span> s, fname <span class="keyword">with</span></span><br><span class="line">...</span><br><span class="line"> | <span class="type">Struct</span> ({ tag = <span class="string">"sockaddr"</span>} <span class="keyword">as</span> s'), <span class="string">"sa_data"</span> -></span><br><span class="line"> <span class="keyword">let</span> f = {ftype; fname; foffset = <span class="number">2</span>} <span class="keyword">in</span></span><br><span class="line"> (s'.fields <- <span class="type">BoxedField</span> f :: s'.fields; f)</span><br><span class="line"> | <span class="type">Struct</span> ({ tag = <span class="string">"sockaddr"</span>} <span class="keyword">as</span> s'), <span class="string">"sa_family"</span> -></span><br><span class="line"> <span class="keyword">let</span> f = {ftype; fname; foffset = <span class="number">1</span>} <span class="keyword">in</span></span><br><span class="line"> (s'.fields <- <span class="type">BoxedField</span> f :: s'.fields; f)</span><br><span class="line"> | <span class="type">View</span> { ty }, _ -></span><br><span class="line"> <span class="keyword">let</span> { ftype; foffset; fname } = field ty fname ftype <span class="keyword">in</span></span><br><span class="line"> { ftype; foffset; fname }</span><br><span class="line"> | _ -> failwith (<span class="string">"Unexpected field "</span>^ fname)</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> <span class="keyword">rec</span> seal : <span class="keyword">type</span> a. a typ -> <span class="built_in">unit</span> = <span class="keyword">function</span></span><br><span class="line">...</span><br><span class="line"> | <span class="type">Struct</span> ({ tag = <span class="string">"sockaddr_storage"</span>; spec = <span class="type">Incomplete</span> _ } <span class="keyword">as</span> s') -></span><br><span class="line"> s'.spec <- <span class="type">Complete</span> { size = <span class="number">128</span>; align = <span class="number">8</span> }</span><br><span class="line"> | <span class="type">Struct</span> ({ tag = <span class="string">"sockaddr"</span>; spec = <span class="type">Incomplete</span> _ } <span class="keyword">as</span> s') -></span><br><span class="line"> s'.spec <- <span class="type">Complete</span> { size = <span class="number">16</span>; align = <span class="number">1</span> }</span><br><span class="line"> | <span class="type">Struct</span> { tag; spec = <span class="type">Complete</span> _ } -></span><br><span class="line"> raise (<span class="type">ModifyingSealedType</span> tag)</span><br><span class="line"> | <span class="type">Union</span> { utag; uspec = <span class="type">Some</span> _ } -></span><br><span class="line"> raise (<span class="type">ModifyingSealedType</span> utag)</span><br><span class="line"> | <span class="type">View</span> { ty } -> seal ty</span><br><span class="line"> | _ -></span><br><span class="line"> raise (<span class="type">Unsupported</span> <span class="string">"Sealing a non-structured type"</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> <span class="symbol">'a</span> const = <span class="symbol">'a</span></span><br><span class="line"><span class="keyword">let</span> constant (<span class="keyword">type</span> t) name (t : t typ) : t = <span class="keyword">match</span> t, name <span class="keyword">with</span></span><br><span class="line"> | _, s -> failwith (<span class="string">"unmatched constant: "</span>^ s)</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> enum (<span class="keyword">type</span> a) name ?typedef ?unexpected (alist : (a * <span class="built_in">int64</span>) <span class="built_in">list</span>) =</span><br><span class="line"> <span class="keyword">match</span> name <span class="keyword">with</span></span><br><span class="line"> | s -></span><br><span class="line"> failwith (<span class="string">"unmatched enum: "</span>^ s)</span><br></pre></td></tr></table></figure> - <p>As you can see, this exports all the offsets required to access the fields inside a <code>sockaddr_t</code> structure. We’re now ready to move to the final stage, which is the actual binding stubs!</p> -<h2 id="Binding-stubs"><a href="#Binding-stubs" class="headerlink" title="Binding stubs"></a>Binding stubs</h2><p>First step in this pass, just like with the previous ones, we need to configure <code>dune</code> to be able to build the exported <code>.ml</code> code from the <code>types</code> pass:</p> +<h2 id="Binding-stubs"><a class="header-anchor" href="#Binding-stubs">¶</a>Binding stubs</h2> +<p>First step in this pass, just like with the previous ones, we need to configure <code>dune</code> to be able to build the exported <code>.ml</code> code from the <code>types</code> pass:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">(rule</span><br><span class="line"> (targets sys_socket_generated_types.ml)</span><br><span class="line"> (deps (:exec ../generator/exec.sh)</span><br><span class="line"> (:gen ../generator/gen_types_c))</span><br><span class="line"> (action (with-stdout-to %{targets}</span><br><span class="line"> (system "%{exec} %{ocaml-config:system} %{gen}"))))</span><br></pre></td></tr></table></figure> - <p>And we can now define the proper bindings. Here’s how it looks like:</p> <figure class="highlight ocaml"><table><tr><td class="code"><pre><span class="line"><span class="keyword">open</span> <span class="type">Ctypes</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">module</span> <span class="type">Def</span> (<span class="type">F</span> : <span class="type">Cstubs</span>.<span class="type">FOREIGN</span>) = <span class="keyword">struct</span></span><br><span class="line"> <span class="keyword">open</span> <span class="type">F</span></span><br><span class="line"></span><br><span class="line"> <span class="keyword">module</span> <span class="type">Types</span> = <span class="type">Sys_socket_types</span>.<span class="type">Def</span>(<span class="type">Sys_socket_generated_types</span>)</span><br><span class="line"></span><br><span class="line"> <span class="keyword">open</span> <span class="type">Types</span></span><br><span class="line"></span><br><span class="line"> <span class="keyword">let</span> getnameinfo = foreign <span class="string">"getnameinfo"</span> (ptr sockaddr_t @-> socklen_t @-> ptr <span class="built_in">char</span> @-> socklen_t @-> ptr <span class="built_in">char</span> @-> socklen_t @-> <span class="built_in">int</span> @-> (returning <span class="built_in">int</span>))</span><br><span class="line"></span><br><span class="line">...</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure> - -<p>As you can see, we’re exporting the <code>getnameinfo</code> function, taking various arguments, including a pointer to a <code>sockaddr_t</code> structure and a couple of <code>socklen_t</code> integers, making use of all the various data types and structures previously defined. The exact specifications of this function can be found <a href="https://pubs.opengroup.org/onlinepubs/009695399/functions/getnameinfo.html">here</a>. We can now define out top-level API..</p> -<h2 id="Final-API"><a href="#Final-API" class="headerlink" title="Final API"></a>Final API</h2><p>Building upon the previous modules, we export various OCaml idiomatic APIs that the binding user can now use to build new bindings against the <code>socket.h</code> APIs.</p> +<p>As you can see, we’re exporting the <code>getnameinfo</code> function, taking various arguments, including a pointer to a <code>sockaddr_t</code> structure and a couple of <code>socklen_t</code> integers, making use of all the various data types and structures previously defined. The exact specifications of this function can be found <a href="https://pubs.opengroup.org/onlinepubs/009695399/functions/getnameinfo.html">here</a>. We can now define out top-level API…</p> +<h2 id="Final-API"><a class="header-anchor" href="#Final-API">¶</a>Final API</h2> +<p>Building upon the previous modules, we export various OCaml idiomatic APIs that the binding user can now use to build new bindings against the <code>socket.h</code> APIs.</p> <p>Just like with the previous steps, first we need to configure the build system:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">(rule</span><br><span class="line"> (targets sys_socket_generated_stubs.ml)</span><br><span class="line"> (deps (:gen ./generator/gen_stubs.exe))</span><br><span class="line"> (action (run %{gen} ml %{targets})))</span><br><span class="line"></span><br><span class="line">(rule</span><br><span class="line"> (targets sys_socket_generated_stubs.c)</span><br><span class="line"> (deps (:gen ./generator/gen_stubs.exe))</span><br><span class="line"> (action (run %{gen} c %{targets})))</span><br></pre></td></tr></table></figure> - <p>This time, we need <code>ocaml-ctypes</code> to generate two compilation units: a <code>.ml</code> file describing the API exported during the <code>stubs</code> phase, as well as the C code to glue it with the C APIs. Here’s the code for that generator:</p> <figure class="highlight ocaml"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> c_headers = <span class="string">"</span></span><br><span class="line"><span class="string">#ifdef _WIN32</span></span><br><span class="line"><span class="string"> #include <winsock2.h></span></span><br><span class="line"><span class="string"> #include <ws2tcpip.h></span></span><br><span class="line"><span class="string">#else</span></span><br><span class="line"><span class="string"> #include <sys/socket.h></span></span><br><span class="line"><span class="string"> #include <netinet/in.h></span></span><br><span class="line"><span class="string"> #include <arpa/inet.h></span></span><br><span class="line"><span class="string"> #include <netdb.h></span></span><br><span class="line"><span class="string">#endif</span></span><br><span class="line"><span class="string">#include <string.h></span></span><br><span class="line"><span class="string">"</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> <span class="literal">()</span> =</span><br><span class="line"> <span class="keyword">let</span> mode = <span class="type">Sys</span>.argv.(<span class="number">1</span>) <span class="keyword">in</span></span><br><span class="line"> <span class="keyword">let</span> fname = <span class="type">Sys</span>.argv.(<span class="number">2</span>) <span class="keyword">in</span></span><br><span class="line"> <span class="keyword">let</span> oc = open_out_bin fname <span class="keyword">in</span></span><br><span class="line"> <span class="keyword">let</span> format =</span><br><span class="line"> <span class="type">Format</span>.formatter_of_out_channel oc</span><br><span class="line"> <span class="keyword">in</span></span><br><span class="line"> <span class="keyword">let</span> fn =</span><br><span class="line"> <span class="keyword">match</span> mode <span class="keyword">with</span></span><br><span class="line"> | <span class="string">"ml"</span> -> <span class="type">Cstubs</span>.write_ml</span><br><span class="line"> | <span class="string">"c"</span> -></span><br><span class="line"> <span class="type">Format</span>.fprintf format <span class="string">"%s@\n"</span> c_headers;</span><br><span class="line"> <span class="type">Cstubs</span>.write_c</span><br><span class="line"> | _ -> <span class="keyword">assert</span> <span class="literal">false</span></span><br><span class="line"> <span class="keyword">in</span></span><br><span class="line"> fn ~concurrency:<span class="type">Cstubs</span>.unlocked format ~prefix:<span class="string">"sys_socket"</span> (<span class="keyword">module</span> <span class="type">Sys_socket_stubs</span>.<span class="type">Def</span>);</span><br><span class="line"> <span class="type">Format</span>.pp_print_flush format <span class="literal">()</span>;</span><br><span class="line"> close_out oc</span><br></pre></td></tr></table></figure> - <p>The exported <code>.ml</code> and <code>.c</code> files are omitted here for simplicity but the reader can generated them themselves from the <code>[ocaml-sys-socket](https://github.com/toots/ocaml-sys-socket)</code> repository if they are curious about their actual content.</p> <p>We can now export our top-level API:</p> <figure class="highlight ocaml"><table><tr><td class="code"><pre><span class="line"><span class="keyword">open</span> <span class="type">Ctypes</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">include</span> <span class="type">Sys_socket_types</span>.<span class="type">SaFamily</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">include</span> <span class="type">Sys_socket_stubs</span>.<span class="type">Def</span>(<span class="type">Sys_socket_generated_stubs</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> socklen = <span class="type">Types</span>.socklen</span><br><span class="line"><span class="keyword">let</span> socklen_t = <span class="type">Types</span>.socklen_t</span><br><span class="line"><span class="keyword">let</span> int_of_socklen = <span class="type">Types</span>.int_of_socklen</span><br><span class="line"><span class="keyword">let</span> socklen_of_int = <span class="type">Types</span>.socklen_of_int</span><br><span class="line"></span><br><span class="line"><span class="keyword">module</span> <span class="type">Sockaddr</span> = <span class="keyword">struct</span></span><br><span class="line"> <span class="keyword">include</span> <span class="type">Types</span>.<span class="type">Sockaddr</span></span><br><span class="line"> <span class="keyword">let</span> from_sockaddr_storage = from_sockaddr_storage t</span><br><span class="line"> <span class="keyword">let</span> sa_data_len = <span class="type">Types</span>.sa_data_len</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> getnameinfo sockaddr_ptr =</span><br><span class="line"> <span class="keyword">let</span> maxhost = <span class="type">Types</span>.ni_maxhost <span class="keyword">in</span></span><br><span class="line"> <span class="keyword">let</span> s = allocate_n <span class="built_in">char</span> ~count:maxhost <span class="keyword">in</span></span><br><span class="line"> <span class="keyword">let</span> maxserv = <span class="type">Types</span>.ni_maxserv <span class="keyword">in</span></span><br><span class="line"> <span class="keyword">let</span> p = allocate_n <span class="built_in">char</span> ~count:maxserv <span class="keyword">in</span></span><br><span class="line"> <span class="keyword">match</span> getnameinfo sockaddr_ptr (socklen_of_int (sizeof sockaddr_t))</span><br><span class="line"> s (socklen_of_int maxhost) </span><br><span class="line"> p (socklen_of_int maxserv)</span><br><span class="line"> (<span class="type">Types</span>.ni_numerichost <span class="keyword">lor</span></span><br><span class="line"> <span class="type">Types</span>.ni_numericserv) <span class="keyword">with</span></span><br><span class="line"> | <span class="number">0</span> -></span><br><span class="line"> <span class="keyword">let</span> host =</span><br><span class="line"> <span class="keyword">let</span> length =</span><br><span class="line"> <span class="type">Unsigned</span>.<span class="type">Size_t</span>.to_int</span><br><span class="line"> (strnlen s (<span class="type">Unsigned</span>.<span class="type">Size_t</span>.of_int maxhost))</span><br><span class="line"> <span class="keyword">in</span></span><br><span class="line"> string_from_ptr s ~length</span><br><span class="line"> <span class="keyword">in</span></span><br><span class="line"> <span class="keyword">let</span> port =</span><br><span class="line"> <span class="keyword">let</span> length =</span><br><span class="line"> <span class="type">Unsigned</span>.<span class="type">Size_t</span>.to_int</span><br><span class="line"> (strnlen p (<span class="type">Unsigned</span>.<span class="type">Size_t</span>.of_int maxserv))</span><br><span class="line"> <span class="keyword">in</span></span><br><span class="line"> <span class="keyword">let</span> port =</span><br><span class="line"> string_from_ptr p ~length</span><br><span class="line"> <span class="keyword">in</span></span><br><span class="line"> <span class="keyword">try</span></span><br><span class="line"> int_of_string port</span><br><span class="line"> <span class="keyword">with</span> _ -></span><br><span class="line"> <span class="keyword">match</span> getservbyname p null <span class="keyword">with</span></span><br><span class="line"> | ptr <span class="keyword">when</span> is_null ptr -> failwith <span class="string">"getnameinfo"</span></span><br><span class="line"> | ptr -></span><br><span class="line"> <span class="type">Unsigned</span>.<span class="type">UInt16</span>.to_int</span><br><span class="line"> (ntohs (!@ (ptr |-> <span class="type">Types</span>.<span class="type">Servent</span>.s_port)))</span><br><span class="line"> <span class="keyword">in</span></span><br><span class="line"> host, port</span><br><span class="line"> | _ -> failwith <span class="string">"getnameinfo"</span></span><br><span class="line"></span><br><span class="line">...</span><br></pre></td></tr></table></figure> - <figure class="highlight ocaml"><table><tr><td class="code"><pre><span class="line"><span class="keyword">open</span> <span class="type">Ctypes</span></span><br><span class="line"></span><br><span class="line"><span class="comment">(** Ctypes routines for C type socklen_t. *)</span></span><br><span class="line"><span class="keyword">type</span> socklen</span><br><span class="line"><span class="keyword">val</span> socklen_t : socklen typ</span><br><span class="line"><span class="keyword">val</span> int_of_socklen : socklen -> <span class="built_in">int</span></span><br><span class="line"><span class="keyword">val</span> socklen_of_int : <span class="built_in">int</span> -> socklen</span><br><span class="line"></span><br><span class="line"><span class="comment">(** Generic sockaddr_t structure. *)</span></span><br><span class="line"><span class="keyword">module</span> <span class="type">Sockaddr</span> : <span class="keyword">sig</span></span><br><span class="line"> <span class="keyword">type</span> t</span><br><span class="line"> <span class="keyword">val</span> t : t structure typ</span><br><span class="line"> <span class="keyword">val</span> sa_family : (sa_family, t structure) field</span><br><span class="line"> <span class="keyword">val</span> sa_data : (<span class="built_in">char</span> carray, t structure) field</span><br><span class="line"> <span class="keyword">val</span> sa_data_len : <span class="built_in">int</span></span><br><span class="line"></span><br><span class="line"> <span class="keyword">val</span> from_sockaddr_storage : <span class="type">SockaddrStorage</span>.t structure ptr -> t structure ptr</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="comment">(** IP address conversion functions. *)</span></span><br><span class="line"><span class="keyword">val</span> getnameinfo : sockaddr ptr -> <span class="built_in">string</span> * <span class="built_in">int</span></span><br><span class="line"></span><br><span class="line">...</span><br></pre></td></tr></table></figure> - <p>That’s it! We now have <code>ocaml-ctypes</code> specific data types and structures that can be used to interface with the host’s native <code>socket.h</code> APIs. Note that we also worked on top of the original low-level binding to <code>getnameinfo</code> to export a higher-level function more idiomatic to the OCaml language.</p> -<h1 id="Lagniappe-cross-compilation-to-Windows"><a href="#Lagniappe-cross-compilation-to-Windows" class="headerlink" title="Lagniappe: cross-compilation to Windows"></a>Lagniappe: cross-compilation to Windows</h1><p>On windows platforms, <code>liquidsoap</code> is compiled using <code>[ocaml-cross-windows](https://github.com/ocaml-cross/opam-cross-windows)</code> and, since windows does have compatible socket APIs, we wanted to also look at cross-compiling for the windows target, which is where we hit a snag on the current <code>dune</code> support.</p> +<h1>Lagniappe: cross-compilation to Windows</h1> +<p>On windows platforms, <code>liquidsoap</code> is compiled using <code>[ocaml-cross-windows](https://github.com/ocaml-cross/opam-cross-windows)</code> and, since windows does have compatible socket APIs, we wanted to also look at cross-compiling for the windows target, which is where we hit a snag on the current <code>dune</code> support.</p> <p>The problem is that, at each intermediary steps, in the case of a cross-compilation, the compiled binaries need to use the target’s OS headers and not the host’s headers, otherwise we end up using offsets specific to e.g. Debian but for a windows binary.</p> <p>In this case, this means that the compiled <code>.exe</code> binaries need to be windows binaries and that we need to execute them as windows native binaries, using <code>[wine](https://www.winehq.org/)</code> .</p> <p><code>dune</code> has a truly amazing <a href="https://dune.readthedocs.io/en/latest/cross-compilation.html">support for cross-compiling</a>, which we do not cover here, but, unfortunately, its primitives for building and executing binaries do not yet cover this use case. Thus we had to trick it into compiling things the way we wanted to do, which why we are using the <code>exec.sh</code> wrapper. Here’s its code:</p> <figure class="highlight sh"><table><tr><td class="code"><pre><span class="line"><span class="meta">#!/bin/sh</span></span><br><span class="line"></span><br><span class="line">SYSTEM=<span class="variable">$1</span></span><br><span class="line">CMD=<span class="variable">$2</span></span><br><span class="line">ARG=<span class="variable">$3</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> <span class="built_in">test</span> <span class="string">"<span class="variable">${SYSTEM}</span>"</span> = <span class="string">"mingw"</span>; <span class="keyword">then</span></span><br><span class="line"> wine <span class="variable">$CMD</span> <span class="variable">$ARG</span></span><br><span class="line"><span class="keyword">elif</span> <span class="built_in">test</span> <span class="string">"<span class="variable">${SYSTEM}</span>"</span> = <span class="string">"mingw64"</span>; <span class="keyword">then</span></span><br><span class="line"> wine64 <span class="variable">$CMD</span> <span class="variable">$ARG</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line"> <span class="variable">$CMD</span> <span class="variable">$ARG</span></span><br></pre></td></tr></table></figure> - <p>Now, you can go back to the previous <code>dune</code> files and see how this wrapper allows to execute binaries according to the system that the corresponding <code>ocamlopt</code> compiler has been configured to build for.</p> -<h1 id="Conclusion"><a href="#Conclusion" class="headerlink" title="Conclusion"></a>Conclusion</h1><p>It’s been a fun time working on this binding! It’s amazing to see the level of details that can be built through <code>ocaml-ctypes</code> using their provided primitives. Ultimately, the binding is very clean and elegant, with very few low-level assumptions.</p> +<h1>Conclusion</h1> +<p>It’s been a fun time working on this binding! It’s amazing to see the level of details that can be built through <code>ocaml-ctypes</code> using their provided primitives. Ultimately, the binding is very clean and elegant, with very few low-level assumptions.</p> <p>Likewise, the simplicity and power of the <code>dune</code> build system makes this very fluid to build. Without it, each of the described steps above would have been much more painful to execute and compile.</p> -<p>[1]: My bet is that, at the time the POSIX specifications were being written, there we already several inconsistent <code>socket.h</code> headers out in the wild among the various historical UNIX flavors..</p> +<p>[1]: My bet is that, at the time the POSIX specifications were being written, there we already several inconsistent <code>socket.h</code> headers out in the wild among the various historical UNIX flavors…</p> ]]></content> <tags> <tag>Technique</tag> @@ -311,7 +304,8 @@ <p>The general idea is simple - we want a fine-grained concurrency primitive, that will let us easily compose chain of operations in sequential manner. Of course we could use threads here, but the question is: are threads fine-grained? In many managed languages with OS threads exposed, they can be quite heavy eg. by default in .NET each thread takes around 1MB of memory and requires calling kernel code to cooperate with other threads, which is an expensive operation on its own.</p> <p>What we’re after, are more lightweight structures (less than 1kB), that can live fully in a user space, so that we can have even millions of them cooperating frequently with each other without heavy performance penalties.</p> <p>Before we begin, I think it’s good to discuss different designs. We’ll cover several different topics to be able to make more informed decisions, that we’re up to apply to our own solution.</p> -<h3 id="Preemptive-vs-cooperative-scheduler"><a href="#Preemptive-vs-cooperative-scheduler" class="headerlink" title="Preemptive vs cooperative scheduler"></a>Preemptive vs cooperative scheduler</h3><p>Scheduler is a subsystem, which direct responsibility is to assign CPU core processing power to a particular fiber. It’s also responsible for coordinating fibers execution. The two most common categories of schedulers are preemptive and cooperative.</p> +<h3 id="Preemptive-vs-cooperative-scheduler"><a class="header-anchor" href="#Preemptive-vs-cooperative-scheduler">¶</a>Preemptive vs cooperative scheduler</h3> +<p>Scheduler is a subsystem, which direct responsibility is to assign CPU core processing power to a particular fiber. It’s also responsible for coordinating fibers execution. The two most common categories of schedulers are preemptive and cooperative.</p> <p>A preemptive scheduler is the one, that’s always in control of fiber execution. It’s able to decide on its own, when fiber can be started and stopped. The most obvious example of such is a thread scheduler existing on most operating systems.</p> <p>Preemptive scheduler usually works in one of two ways:</p> <ul> @@ -322,20 +316,24 @@ <p>A cooperative scheduler doesn’t have a concept of preemption - once started by the scheduler, a fiber will execute until it doesn’t give back the control willingly. This is often done with dedicated programming constructs, and often is known as yielding, parking or awaiting.</p> <p>In cooperative variant, a fiber body is usually split into series of discrete steps, between which fiber gives control back to the scheduler.</p> <p>Keep in mind that these two are not mutually exclusive - a preemptive scheduler often provides a way for a fiber to return control back to it when it’s known that fiber won’t be executing any longer eg. because it has been put to sleep for a while.</p> -<h3 id="Stackless-vs-stackful"><a href="#Stackless-vs-stackful" class="headerlink" title="Stackless vs. stackful"></a>Stackless vs. stackful</h3><p>A concept, that’s somewhat related to a topic above is the idea of stackless and stackful coroutines.</p> -<p>A stackful variant is aware of underlying execution stack and can preserve/restore parts of it when yielding/continuing a fiber. Examples of this approach could be Go, Lua, Python asyncio and in the future, also <a href="https://www.youtube.com/watch?v=NV46KFV1m-4&ref=bartoszsypytkowski.com">Java Loom</a> project. Implementing such option (if it’s not implemented by a runtime already) usually requires diving deep into low-level internals, since execution stack is not something that most managed languages offers the users to play with, and doing so without coordination with runtime can cause problems - like determining liveness of objects for GC purposes.</p> +<h3 id="Stackless-vs-stackful"><a class="header-anchor" href="#Stackless-vs-stackful">¶</a>Stackless vs. stackful</h3> +<p>A concept, that’s somewhat related to a topic above is the idea of stackless and stackful coroutines.</p> +<p>A stackful variant is aware of underlying execution stack and can preserve/restore parts of it when yielding/continuing a fiber. Examples of this approach could be Go, Lua, Python asyncio and in the future, also <a href="https://www.youtube.com/watch?v=NV46KFV1m-4&ref=bartoszsypytkowski.com">Java Loom</a> project. Implementing such option (if it’s not implemented by a runtime already) usually requires diving deep into low-level internals, since execution stack is not something that most managed languages offers the users to play with, and doing so without coordination with runtime can cause problems - like determining liveness of objects for GC purposes.</p> <p>Stackless coroutine usually captures locals that we want to preserve as part of callback object (lambda), that is allocated as an object on the heap and scheduled on yield continuation. These steps are usually visible directly in code (eg. await in C#, Rust and JavaScript, but also joints of Scala for-comprehensions, bang-suffix in F# or Haskell do-notation), but sometimes can be implicit like in case of Kotlin. Take into account that while many languages offer syntax support for those constructs, it’s not explicitly necessary to work - take a look at JavaScript and <code>Promise.then</code> as an example.</p> <p>Stackless coroutines usually construct their logic around one of two concepts:</p> <ol> <li>Finite state machines - this variant is usually faster and can be encoded manually (example of such case is Akka actors), but for a human eye it usually doesn’t really read as a sequential step-by-step program execution, unless it has some support from the compiler itself (see: C# and Rust).</li> -<li>Monadic sequencing via bind/flatMap operator, which is very popular in functional languages. While we cover it in more details in the rest of this blog post, for now it’s enough to say that it’s a way to chain callback-based behaviors together in a way, that resembles standard sequential code.</li> +<li>Monadic sequencing via bind/flatMap operator, which is very popular in functional languages. While we cover it in more details in the rest of this blog post, for now it’s enough to say that it’s a way to chain callback-based behaviors together in a way, that resembles standard sequential code.</li> </ol> -<p>For sure one of the advantages of stackful coroutines is that they’re <em>mono-colored</em>: you can yield/continue coroutine execution from within any other function, while in the stackless variant splits your world into <em>two-colored</em> functions - synchronous and asynchronous - where async one can be only called and yielded safely (without blocking underlying OS thread) from within another async function.</p> -<h3 id="Eager-vs-lazy-fibers"><a href="#Eager-vs-lazy-fibers" class="headerlink" title="Eager vs lazy fibers"></a>Eager vs lazy fibers</h3><p>We already mentioned two important events in fiber execution life cycle - starting and parking. Here I briefly discuss about different design decisions on when to start a fiber execution.</p> +<p>For sure one of the advantages of stackful coroutines is that they’re <em>mono-colored</em>: you can yield/continue coroutine execution from within any other function, while in the stackless variant splits your world into <em>two-colored</em> functions - synchronous and asynchronous - where async one can be only called and yielded safely (without blocking underlying OS thread) from within another async function.</p> +<h3 id="Eager-vs-lazy-fibers"><a class="header-anchor" href="#Eager-vs-lazy-fibers">¶</a>Eager vs lazy fibers</h3> +<p>We already mentioned two important events in fiber execution life cycle - starting and parking. Here I briefly discuss about different design decisions on when to start a fiber execution.</p> <p>Eager execution means, that fiber is started automatically after its creation. An example of such are Scala <code>Future[A]</code> and JavaScript <code>Promise</code>. Since execution process starts right away, we’re willingly resign from a certain degree of control over how or when to execute given fiber. Usually this is solved by wrapping a fiber creation into another function or lambda.</p> <p>Lazy execution is much more common and preferred way of work, as it allows us to separate place where we want to define our asynchronous sequence of steps from the place, where the execution details are defined. It’s used in C# TPL as well as pretty much in all functional languages implementations (excluding Scala futures mentioned earlier).</p> -<h3 id="Interruption"><a href="#Interruption" class="headerlink" title="Interruption"></a>Interruption</h3><p>There are also few decisions regarding premature escaping the fiber execution, also known as interruption/cancelation: one of them requires passing special object - a token - between method calls and explicit checking for its completion. It is how C# Tasks work. However putting such requirement onto the API user can be cumbersome and error-prone option. Therefore pretty much every other coroutine library either allows to direcly interrupt a fiber or (like in case of F# Async) passes cancelation tokens and check if they were triggered under the hood.</p> -<h2 id="Implementation"><a href="#Implementation" class="headerlink" title="Implementation"></a>Implementation</h2><p>Since we talked a bit about various approaches, let’s get to the meat of this blog post: implementing our own coroutine library in F#. So, what properties will it have?:</p> +<h3 id="Interruption"><a class="header-anchor" href="#Interruption">¶</a>Interruption</h3> +<p>There are also few decisions regarding premature escaping the fiber execution, also known as interruption/cancelation: one of them requires passing special object - a token - between method calls and explicit checking for its completion. It is how C# Tasks work. However putting such requirement onto the API user can be cumbersome and error-prone option. Therefore pretty much every other coroutine library either allows to direcly interrupt a fiber or (like in case of F# Async) passes cancelation tokens and check if they were triggered under the hood.</p> +<h2 id="Implementation"><a class="header-anchor" href="#Implementation">¶</a>Implementation</h2> +<p>Since we talked a bit about various approaches, let’s get to the meat of this blog post: implementing our own coroutine library in F#. So, what properties will it have?:</p> <ol> <li>We use cooperative scheduling (we don’t want to tweak the compiler) of stackless fibers with support from F# computation expression for nice syntax.</li> <li>We use simple approach by defining custom <code>bind</code> operator with support from F# computation expressions. No state machines.</li> @@ -345,31 +343,26 @@ <p>All of these give us in very similar approach to that found inside of native F# <code>Async</code> data type. To begin with, we’ll simply define the shape of our fiber.</p> <p>Underneath, pretty much every cooperative stackless coroutine approach uses callbacks to drive the flow of synchronous segments of code to be executed one after another. So what we need is a callback which takes a result of previous coroutine and schedules in within some context of execution:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">type</span> <span class="title class_">Fiber</span><span class="operator"><</span><span class="symbol">'a</span><span class="operator">></span> <span class="operator">=</span> Fiber <span class="keyword">of</span> (ExecutionContext <span class="operator">-></span> FiberCallback<span class="operator"><</span><span class="symbol">'a</span><span class="operator">></span> <span class="operator">-></span> <span class="type">unit</span>)</span><br></pre></td></tr></table></figure> - <p>Here we’ll represent Fiber as a simple single-case discriminated union. We could as well define other specialized cases, like:</p> <ul> <li>Situation when coroutine is executed immediately and doesn’t need to be awaited on: think about variant of <code>ValueTask</code> from C# Task Parallel Library.</li> <li>Case when coroutine fails - in that case we might want to store an artificial tracing context that would allow us to create nicely-formatted “stack traces”: since .NET Core 2.1, C# already provides similar solution however AFAIK it’s been solved differently.</li> </ul> -<p>Ok, but what are <code>ExecutionContext</code> and <code>FiberCallback<'a></code>? Let’s start from callback. We can represent it as follows:</p> +<p>Ok, but what are <code>ExecutionContext</code> and <code>FiberCallback<'a></code>? Let’s start from callback. We can represent it as follows:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">type</span> <span class="title class_">FiberCallback</span><span class="operator"><</span><span class="symbol">'a</span><span class="operator">></span> <span class="operator">=</span> FiberResult<span class="operator"><</span><span class="symbol">'a</span><span class="operator">></span> <span class="operator">-></span> unit</span><br></pre></td></tr></table></figure> - -<p>It’s just a simple function, which takes result of previous fiber execution and handles it. What’s the <code>FiberResult<'a></code> then?</p> -<p>Our fiber can complete successfully (returning a value) or fail with an exception. We’ll be conservative here and won’t go into more typed world of <a href="http://degoes.net/articles/bifunctor-io?ref=bartoszsypytkowski.com">IO bifunctor</a>. We can easy define these possible outputs in F# using <code>Result<'a, exn></code>.</p> +<p>It’s just a simple function, which takes result of previous fiber execution and handles it. What’s the <code>FiberResult<'a></code> then?</p> +<p>Our fiber can complete successfully (returning a value) or fail with an exception. We’ll be conservative here and won’t go into more typed world of <a href="http://degoes.net/articles/bifunctor-io?ref=bartoszsypytkowski.com">IO bifunctor</a>. We can easy define these possible outputs in F# using <code>Result<'a, exn></code>.</p> <p>Question is: is that exhaustive? Well… no. As we already mentioned, there’s a 3rd state, often overlooked or conflated with failure: a canceled fiber. A canceled fiber doesn’t produce any output - since it was canceled before completion. In F# we already know how to represent an absence of value - simply use an option. Therefore our ultimate Fiber result type could look like this:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">type</span> <span class="title class_">FiberResult</span><span class="operator"><</span><span class="symbol">'a</span><span class="operator">></span> <span class="operator">=</span> Result<span class="operator"><</span><span class="symbol">'a</span>, exn<span class="operator">></span> option</span><br></pre></td></tr></table></figure> - <p>Now, the <code>ExecutionContext</code>. While it can be compound of many different capabilities throughout the system - even to serve as functional equivalent of dependency injection - here I’ll use it only for implicit passing of specific scheduler info and cancelation tokens from one fiber to another.</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">type</span> <span class="title class_">ExecutionContext</span> <span class="operator">=</span> IScheduler <span class="operator">*</span> Cancel</span><br></pre></td></tr></table></figure> - <p><code>IScheduler</code> interface is used to abstract component responsible for running our fibers. At the moment all we need is an ability to schedule fiber execution:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="meta">[<Interface>]</span></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">IScheduler</span> <span class="operator">=</span> </span><br><span class="line"> <span class="keyword">abstract</span> Schedule<span class="operator">:</span> (<span class="type">unit</span> <span class="operator">-></span> <span class="type">unit</span>) <span class="operator">-></span> <span class="type">unit</span></span><br></pre></td></tr></table></figure> - <p>While the name and signature imply multithreaded execution model, it doesn’t have to be the case. We can even implement scheduler which will simulate everything on a single core.</p> <p>For now, we can simply implement a scheduler API on top of our standard .NET thread pool:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">module</span> Scheduler</span><br><span class="line"></span><br><span class="line"><span class="keyword">open</span> System.Threading</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> shared <span class="operator">=</span> </span><br><span class="line"> { <span class="keyword">new</span> ISchedule <span class="keyword">with</span></span><br><span class="line"> <span class="keyword">member</span> __.Schedule fn <span class="operator">=</span> </span><br><span class="line"> ThreadPool.QueueUserWorkItem(WaitCallback (<span class="keyword">fun</span> _ <span class="operator">-></span> fn())) <span class="operator">|></span> <span class="built_in">ignore</span> }</span><br></pre></td></tr></table></figure> - -<h3 id="Cancellation"><a href="#Cancellation" class="headerlink" title="Cancellation"></a>Cancellation</h3><p>Now it’s a time for cancellation tokens. Of course we could just make use of a flag - conceptually working like native .NET <code>CancellationToken</code>. However given implicit cancellation, it may not be enough. Example:</p> +<h3 id="Cancellation"><a class="header-anchor" href="#Cancellation">¶</a>Cancellation</h3> +<p>Now it’s a time for cancellation tokens. Of course we could just make use of a flag - conceptually working like native .NET <code>CancellationToken</code>. However given implicit cancellation, it may not be enough. Example:</p> <blockquote> <p>Imagine, that inside our fiber we’re scheduling the race between two other fibers ie. one writing data to a file and other which will complete after timeout. Now, whenever one of them completes first, we want to cancel another one to stop wasting resources for result that no longer matters.</p> </blockquote> @@ -381,21 +374,21 @@ </ol> <p>This behavior implies at least using two separate tokens, however in practice it will be more pragmatic to make our <code>Cancel</code> token work as a tree hierarchy - this way we can easily keep track of things and support more complex scenarios.</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="meta">[<Sealed;AllowNullLiteral>]</span></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">Cancel</span>(parent<span class="operator">:</span> Cancel) <span class="operator">=</span></span><br><span class="line"> <span class="keyword">let</span> <span class="keyword">mutable</span> flag<span class="operator">:</span> <span class="type">int</span> <span class="operator">=</span> <span class="number">0</span></span><br><span class="line"> <span class="keyword">let</span> <span class="keyword">mutable</span> children<span class="operator">:</span> Cancel <span class="type">list</span> <span class="operator">=</span> []</span><br><span class="line"> <span class="keyword">new</span>() <span class="operator">=</span> Cancel(<span class="literal">null</span>)</span><br><span class="line"> <span class="comment">/// Check if token was cancelled</span></span><br><span class="line"> <span class="keyword">member</span> __.Cancelled <span class="operator">=</span> flag <span class="operator">=</span> <span class="number">1</span></span><br><span class="line"> <span class="comment">/// Remove child token</span></span><br><span class="line"> <span class="keyword">member</span> <span class="keyword">private</span> __.RemoveChild(child) <span class="operator">=</span> </span><br><span class="line"> <span class="keyword">let</span> <span class="keyword">rec</span> loop child <span class="operator">=</span></span><br><span class="line"> <span class="keyword">let</span> children' <span class="operator">=</span> children</span><br><span class="line"> <span class="keyword">let</span> nval <span class="operator">=</span> children' <span class="operator">|></span> List.filter ((<span class="operator"><></span>) child)</span><br><span class="line"> <span class="keyword">if</span> <span class="built_in">not</span> (obj.ReferenceEquals(children', Interlocked.CompareExchange(<span class="operator">&</span>children, nval, children')))</span><br><span class="line"> <span class="keyword">then</span> loop child</span><br><span class="line"> <span class="keyword">if</span> <span class="built_in">not</span> (List.isEmpty children) <span class="keyword">then</span> loop child</span><br><span class="line"> <span class="comment">/// Create a new child token and return it.</span></span><br><span class="line"> <span class="keyword">member</span> this.AddChild () <span class="operator">=</span></span><br><span class="line"> <span class="keyword">let</span> <span class="keyword">rec</span> loop child <span class="operator">=</span></span><br><span class="line"> <span class="keyword">let</span> children' <span class="operator">=</span> children</span><br><span class="line"> <span class="keyword">if</span> (obj.ReferenceEquals(children', Interlocked.CompareExchange(<span class="operator">&</span>children, child<span class="operator">::</span>children', children')))</span><br><span class="line"> <span class="keyword">then</span> child</span><br><span class="line"> <span class="keyword">else</span> loop child</span><br><span class="line"> loop (Cancel this)</span><br><span class="line"> <span class="comment">/// Cancel a token</span></span><br><span class="line"> <span class="keyword">member</span> this.Cancel() <span class="operator">=</span></span><br><span class="line"> <span class="keyword">if</span> Interlocked.Exchange(<span class="operator">&</span>flag, <span class="number">1</span>) <span class="operator">=</span> <span class="number">0</span> <span class="keyword">then</span></span><br><span class="line"> <span class="keyword">for</span> child <span class="keyword">in</span> Interlocked.Exchange(<span class="operator">&</span>children, []) <span class="keyword">do</span> child.Cancel()</span><br><span class="line"> <span class="keyword">if</span> <span class="built_in">not</span> (isNull parent) <span class="keyword">then</span> parent.RemoveChild(this)</span><br><span class="line"></span><br></pre></td></tr></table></figure> - <p>The general idea is simple: every new cancellation token (except root) may have a parent and a list of children. Canceling parent means canceling its children as well. After cancellation, we need to unpin child from its parent (therefore need for <code>RemveChild</code> operation) to avoid memory leaks.</p> -<h5 id="Lock-free-updates"><a href="#Lock-free-updates" class="headerlink" title="Lock-free updates"></a>Lock-free updates</h5><p>What might be confusing for some in the code above, are recursive loops inside of <code>AddChild</code>/<code>RemoveChild</code> operations. This is a good place to introduce lock-free algorithms: we use atomic operations from <a href="https://www.bartoszsypytkowski.com/building-custom-fibers-library-in-f/docs.microsoft.com/en-us/dotnet/api/system.threading.interlocked">Interlocked</a> class to make sure that we can replace field references within a single CPU instruction, therefore making such field update safe without synchronized access. This is also known as Compare-And-Swap semantics.</p> -<p>This alone however is not enough, as <code>Interlocked.CompareExchange(&field, new', old)</code> can only safely replace a single field with new value if it contained an old one. This means that you cannot safely add or remove element to the list. So what can we do?</p> +<h5 id="Lock-free-updates"><a class="header-anchor" href="#Lock-free-updates">¶</a>Lock-free updates</h5> +<p>What might be confusing for some in the code above, are recursive loops inside of <code>AddChild</code>/<code>RemoveChild</code> operations. This is a good place to introduce lock-free algorithms: we use atomic operations from <a href="https://www.bartoszsypytkowski.com/building-custom-fibers-library-in-f/docs.microsoft.com/en-us/dotnet/api/system.threading.interlocked">Interlocked</a> class to make sure that we can replace field references within a single CPU instruction, therefore making such field update safe without synchronized access. This is also known as Compare-And-Swap semantics.</p> +<p>This alone however is not enough, as <code>Interlocked.CompareExchange(&field, new', old)</code> can only safely replace a single field with new value if it contained an old one. This means that you cannot safely add or remove element to the list. So what can we do?</p> <ol> <li>We’re taking a value from the field.</li> <li>Update that value.</li> <li>Conditionally put it back again. What if in the meantime the field was already replaced by another concurrently running thread? In that case <code>Interlocked.CompareExchange</code> will return field value other that the one we read in step 1. This is why we compare its result with the variable we expected.</li> -<li>If the expectation fails, we’ll retry - hence a recursive loop. Eventually even in high contention scenarios we should be able to complete after few retries. Given cheap and idempotent update operation, this still will be way faster than trying to call kernel code to obtain mutex/semaphore lock.</li> +<li>If the expectation fails, we’ll retry - hence a recursive loop. Eventually even in high contention scenarios we should be able to complete after few retries. Given cheap and idempotent update operation, this still will be way faster than trying to call kernel code to obtain mutex/semaphore lock.</li> </ol> <p>While this may sound like something error prone - we can potentially add the same element multiple times - in practice it’s safe, because our collection here is an immutable data structure. Adding the same element multiple times without updating the reference will always produce the same result.</p> -<h3 id="Back-on-track…"><a href="#Back-on-track…" class="headerlink" title="Back on track…"></a>Back on track…</h3><p>Now we have pretty much all core structures. We’re ready to start building our fiber operators. Starting from the basic ones - a successfully completed fiber and the failed one:</p> +<h3 id="Back-on-track…"><a class="header-anchor" href="#Back-on-track…">¶</a>Back on track…</h3> +<p>Now we have pretty much all core structures. We’re ready to start building our fiber operators. Starting from the basic ones - a successfully completed fiber and the failed one:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> success r <span class="operator">=</span> Fiber <span class="operator"><|</span> <span class="keyword">fun</span> (_, c) next <span class="operator">-></span> </span><br><span class="line"> <span class="keyword">if</span> c.Cancelled <span class="keyword">then</span> next <span class="literal">None</span> <span class="keyword">else</span> next (<span class="literal">Some</span> (<span class="literal">Ok</span> r))</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> fail ex <span class="operator">=</span> Fiber <span class="operator"><|</span> <span class="keyword">fun</span> (_, c) next <span class="operator">-></span> </span><br><span class="line"> <span class="keyword">if</span> c.Cancelled <span class="keyword">then</span> next <span class="literal">None</span> <span class="keyword">else</span> next (<span class="literal">Some</span> (<span class="literal">Error</span> ex))</span><br></pre></td></tr></table></figure> - -<p>Here, we simply pass a result/error to our Fiber callback:</p> +<p>Here, we simply pass a result/error to our Fiber callback:</p> <ul> <li>Cancelled fiber call <code>next</code> callback with <code>None</code> - as fibers cancelled before completion produce output .</li> <li>Successful call results in passing <code>Some (Ok result)</code> to a callback…</li> @@ -404,41 +397,36 @@ <p>You’ll be able to see a cancellation check made here as preamble of pretty much every operator body, which we’ll define. While it may sound cumbersome remember: we do that so that users of our fibers won’t have to :)</p> <p>Next very important operation is result mapping - we want to map result of one fiber into something else, returning another (lazy) fiber:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> mapResult (fn<span class="operator">:</span> <span class="type">Result</span><span class="operator"><</span><span class="symbol">'a</span><span class="operator">></span> <span class="operator">-></span> <span class="type">Result</span><span class="operator"><</span><span class="symbol">'b</span><span class="operator">></span>) (Fiber call) <span class="operator">=</span> Fiber <span class="operator"><|</span> <span class="keyword">fun</span> (s, c) next <span class="operator">-></span></span><br><span class="line"> <span class="keyword">if</span> c.Cancelled <span class="keyword">then</span> next <span class="literal">None</span></span><br><span class="line"> <span class="keyword">else</span> </span><br><span class="line"> <span class="keyword">try</span> </span><br><span class="line"> call (s, c) (<span class="keyword">fun</span> result <span class="operator">-></span></span><br><span class="line"> <span class="keyword">if</span> c.Cancelled <span class="keyword">then</span> next <span class="literal">None</span></span><br><span class="line"> <span class="keyword">else</span> next (Option.map fn result))</span><br><span class="line"> <span class="keyword">with</span> e <span class="operator">-></span> next (<span class="literal">Some</span> (<span class="literal">Error</span> e))</span><br></pre></td></tr></table></figure> - <p>We can use this function to compose more traditionally-looking <code>map</code> function…</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> map (fn<span class="operator">:</span> <span class="symbol">'a</span> <span class="operator">-></span> <span class="symbol">'b</span>) fiber <span class="operator">=</span> mapResult (Result.map fn) fiber</span><br></pre></td></tr></table></figure> - -<p>… however <code>mapResult</code> is more powerful - you could easily imagine using to apply failure recovery (a.k.a <code>try</code>/<code>catch</code> semantics) by simply mapping <code>Error exception</code> → <code>Ok recoveredValue</code>:</p> +<p>… however <code>mapResult</code> is more powerful - you could easily imagine using to apply failure recovery (a.k.a <code>try</code>/<code>catch</code> semantics) by simply mapping <code>Error exception</code> → <code>Ok recoveredValue</code>:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> catch fn fiber <span class="operator">=</span> mapResult (<span class="keyword">function</span> <span class="literal">Error</span> e <span class="operator">-></span> fn e <span class="operator">|</span> ok <span class="operator">-></span> ok) fiber</span><br></pre></td></tr></table></figure> - <p>Another must-have function is binding operator (also know as <code>flatMap</code> in other languages like Scala, or <code>Promise.then</code> in JavaScript). It gives us the ability to compose fibers together - we’ll also use it when we come up to building a computation expression for our fibers.</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> bind (fn<span class="operator">:</span> <span class="symbol">'a</span> <span class="operator">-></span> Fiber<span class="operator"><</span><span class="symbol">'b</span><span class="operator">></span>) (Fiber call) <span class="operator">=</span> Fiber <span class="operator"><|</span> <span class="keyword">fun</span> (s, c) next <span class="operator">-></span></span><br><span class="line"> <span class="keyword">if</span> c.Cancelled <span class="keyword">then</span> next <span class="literal">None</span> </span><br><span class="line"> <span class="keyword">else</span> </span><br><span class="line"> <span class="keyword">try</span></span><br><span class="line"> call (s, c) (<span class="keyword">fun</span> result <span class="operator">-></span></span><br><span class="line"> <span class="keyword">if</span> c.Cancelled <span class="keyword">then</span> next <span class="literal">None</span></span><br><span class="line"> <span class="keyword">else</span> <span class="keyword">match</span> result <span class="keyword">with</span></span><br><span class="line"> <span class="operator">|</span> <span class="literal">Some</span> (<span class="literal">Ok</span> r) <span class="operator">-></span></span><br><span class="line"> <span class="keyword">let</span> (Fiber call2) <span class="operator">=</span> fn r</span><br><span class="line"> call2 (s, c) next <span class="comment">// pass `next` callback over to next fiber</span></span><br><span class="line"> <span class="operator">|</span> <span class="literal">None</span> <span class="operator">-></span> next <span class="literal">None</span></span><br><span class="line"> <span class="operator">|</span> <span class="literal">Some</span> (<span class="literal">Error</span> e) <span class="operator">-></span> next (<span class="literal">Some</span>(<span class="literal">Error</span> e)))</span><br><span class="line"> <span class="keyword">with</span> e <span class="operator">-></span> next (<span class="literal">Some</span>(<span class="literal">Error</span> e))</span><br></pre></td></tr></table></figure> - <p>It’s simple - we execute one fiber from within another, passing the <code>next</code> callback from outer function as an argument to inner one.</p> -<h3 id="Fiber-computation-expressions"><a href="#Fiber-computation-expressions" class="headerlink" title="Fiber computation expressions"></a>Fiber computation expressions</h3><p>With these few functions we’re already prepared to build a basic computation expression, that will enable us programming with fibers in pleasant way:</p> +<h3 id="Fiber-computation-expressions"><a class="header-anchor" href="#Fiber-computation-expressions">¶</a>Fiber computation expressions</h3> +<p>With these few functions we’re already prepared to build a basic computation expression, that will enable us programming with fibers in pleasant way:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="meta">[<Struct>]</span></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">FiberBuilder</span> <span class="operator">=</span></span><br><span class="line"> <span class="keyword">member</span> <span class="keyword">inline</span> __.Zero <span class="operator">=</span> Fiber.success (Unchecked.defaultof<span class="operator"><</span>_<span class="operator">></span>)</span><br><span class="line"> <span class="keyword">member</span> <span class="keyword">inline</span> __.ReturnFrom fib <span class="operator">=</span> fib</span><br><span class="line"> <span class="keyword">member</span> <span class="keyword">inline</span> __.Return value <span class="operator">=</span> Fiber.success value</span><br><span class="line"> <span class="keyword">member</span> <span class="keyword">inline</span> __.Bind(fib, fn) <span class="operator">=</span> Fiber.bind fn fib</span><br><span class="line"></span><br><span class="line"><span class="meta">[<AutoOpen>]</span></span><br><span class="line"><span class="keyword">module</span> FiberBuilder <span class="operator">=</span></span><br><span class="line"></span><br><span class="line"> <span class="keyword">let</span> fib <span class="operator">=</span> FiberBuilder()</span><br></pre></td></tr></table></figure> - <p>While in F# <a href="https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/computation-expressions?ref=bartoszsypytkowski.com">there are many more operators</a> we could pack into our computation expression, these are basic ones that will let it work. With such construct, we’ll be able to write programs like:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> <span class="keyword">inline</span> millis n <span class="operator">=</span> TimeSpan.FromMilliseconds (float n)</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> program<span class="operator">:</span> Fiber<span class="operator"><</span><span class="type">int</span><span class="operator">></span> <span class="operator">=</span> <span class="keyword">fib</span> {</span><br><span class="line"> <span class="keyword">let</span> a <span class="operator">=</span> <span class="keyword">fib</span> {</span><br><span class="line"> <span class="keyword">do!</span> Fiber.delay (millis <span class="number">1000</span>) <span class="comment">// create some artificial delay</span></span><br><span class="line"> <span class="keyword">return</span> <span class="number">3</span></span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">let!</span> b <span class="operator">=</span> a <span class="operator">|></span> Fiber.timeout (millis <span class="number">3000</span>) <span class="comment">// execute task within specified timeout</span></span><br><span class="line"> <span class="keyword">return</span> b }</span><br></pre></td></tr></table></figure> - <p>Sure, we have neither delay nor timeout operators at the moment, but at least you know where are we heading now :)</p> -<h3 id="Delayed-execution"><a href="#Delayed-execution" class="headerlink" title="Delayed execution"></a>Delayed execution</h3><p>In order to implement delays, we could theoretically just call <code>Thread.Sleep</code> and get over it, but this approach is devastating from any coroutine library point of view. Most user-space thread libraries work by using a predefined fixed pool of OS-level threads and scheduling coroutines on them - you can read more about building thread pools <a href="https://www.bartoszsypytkowski.com/thread-safety-with-affine-thread-pools/">here</a>.</p> +<h3 id="Delayed-execution"><a class="header-anchor" href="#Delayed-execution">¶</a>Delayed execution</h3> +<p>In order to implement delays, we could theoretically just call <code>Thread.Sleep</code> and get over it, but this approach is devastating from any coroutine library point of view. Most user-space thread libraries work by using a predefined fixed pool of OS-level threads and scheduling coroutines on them - you can read more about building thread pools <a href="https://www.bartoszsypytkowski.com/thread-safety-with-affine-thread-pools/">here</a>.</p> <p>However, <code>Thread.Sleep(timeout)</code> doesn’t know thread pooling mechanism - all it knows about is that we called suspending current OS thread of execution. This means, that this thread will not be awoken by kernel until timeout completes. What it means, is that none of our fibers will be able to use that thread. This is bad, because usually thread pools are made to fit in-line with number of machine CPU cores. In practice, <code>Thread.Sleep</code> may keep one of our CPU cores idle, wasting machine power in the process.</p> <p>For this reason we usually want to build a suspendable fibers, that will respect our thread pool. This however cannot be done without cooperation with scheduler itself. Therefore, we need to extend API of our scheduler:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">type</span> <span class="title class_">IScheduler</span> <span class="operator">=</span></span><br><span class="line"> <span class="keyword">abstract</span> Schedule<span class="operator">:</span> (<span class="type">unit</span> <span class="operator">-></span> <span class="type">unit</span>) <span class="operator">-></span> <span class="type">unit</span></span><br><span class="line"> <span class="keyword">abstract</span> Delay<span class="operator">:</span> TimeSpan <span class="operator">*</span> (<span class="type">unit</span> <span class="operator">-></span> <span class="type">unit</span>) <span class="operator">-></span> <span class="type">unit</span></span><br></pre></td></tr></table></figure> - <p>And our simple implementation of it as well:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> shared <span class="operator">=</span> </span><br><span class="line"> { <span class="keyword">new</span> IScheduler <span class="keyword">with</span></span><br><span class="line"> <span class="keyword">member</span> __.Schedule fn <span class="operator">=</span> <span class="operator">....</span></span><br><span class="line"> <span class="keyword">member</span> this.Delay (timeout<span class="operator">:</span> TimeSpan, fn) <span class="operator">=</span> </span><br><span class="line"> <span class="keyword">let</span> <span class="keyword">mutable</span> t <span class="operator">=</span> Unchecked.defaultof<span class="operator"><</span>Timer<span class="operator">></span></span><br><span class="line"> <span class="keyword">let</span> callback <span class="operator">=</span> <span class="keyword">fun</span> _ <span class="operator">-></span> </span><br><span class="line"> t.Dispose()</span><br><span class="line"> fn()</span><br><span class="line"> ()</span><br><span class="line"> t <span class="operator"><-</span> <span class="keyword">new</span> Timer(callback, <span class="literal">null</span>, int timeout.TotalMilliseconds, Timeout.Infinite)</span><br><span class="line"> }</span><br></pre></td></tr></table></figure> - <p>We’ll use a .NET timers here to implement our delays. With these in our hands, our<code>Fiber.delay</code> operation is trivial to implement:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> delay (timeout)<span class="operator">:</span> Fiber<span class="operator"><</span><span class="type">unit</span><span class="operator">></span> <span class="operator">=</span></span><br><span class="line"> Fiber <span class="operator"><|</span> <span class="keyword">fun</span> (s, c) next <span class="operator">-></span></span><br><span class="line"> <span class="keyword">if</span> c.Cancelled <span class="keyword">then</span> next <span class="literal">None</span></span><br><span class="line"> <span class="keyword">else</span> s.Delay(timeout, <span class="keyword">fun</span> () <span class="operator">-></span> </span><br><span class="line"> <span class="keyword">if</span> c.Cancelled </span><br><span class="line"> <span class="keyword">then</span> next <span class="literal">None</span> </span><br><span class="line"> <span class="keyword">else</span> next (<span class="literal">Some</span> (<span class="literal">Ok</span> ())))</span><br></pre></td></tr></table></figure> - -<h3 id="Composing-parallel-fibers"><a href="#Composing-parallel-fibers" class="headerlink" title="Composing parallel fibers"></a>Composing parallel fibers</h3><p>We’re slowly getting to the end. What I left for this blog post was to implement two basic operators, that are prevalent in most coroutine libraries:</p> +<h3 id="Composing-parallel-fibers"><a class="header-anchor" href="#Composing-parallel-fibers">¶</a>Composing parallel fibers</h3> +<p>We’re slowly getting to the end. What I left for this blog post was to implement two basic operators, that are prevalent in most coroutine libraries:</p> <ul> <li><code>Fiber.parallel</code> which will schedule multiple fibers to run in parallel and returns a fiber which aggregates their results.</li> <li>Running two fibers in parallel and returning the result of whichever completes first, while cancelling a second one. We already discussed this approach before. Here I’ll call it <code>Fiber.race</code>.</li> </ul> -<h4 id="Aggregating-parallel-results"><a href="#Aggregating-parallel-results" class="headerlink" title="Aggregating parallel results"></a>Aggregating parallel results</h4><p>We’ll start from building a parallel operator, which will change our array of fibers into fiber with an array of results. But let’s define the semantics of that operation first:</p> +<h4 id="Aggregating-parallel-results"><a class="header-anchor" href="#Aggregating-parallel-results">¶</a>Aggregating parallel results</h4> +<p>We’ll start from building a parallel operator, which will change our array of fibers into fiber with an array of results. But let’s define the semantics of that operation first:</p> <ul> <li>Our result fiber completes only when all of the aggregated fibers completed with successful result.</li> <li>If any of the fibers fails, the resulting fiber also fails.</li> @@ -446,32 +434,28 @@ </ul> <p>The core skeleton of that operation could look like following:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> parallel (fibers<span class="operator">:</span> Fiber<span class="operator"><</span><span class="symbol">'a</span><span class="operator">></span>[])<span class="operator">:</span> Fiber<span class="operator"><</span><span class="symbol">'a</span>[]<span class="operator">></span> <span class="operator">=</span></span><br><span class="line"> Fiber <span class="operator"><|</span> <span class="keyword">fun</span> (s, c) next <span class="operator">-></span></span><br><span class="line"> <span class="keyword">if</span> c.Cancelled <span class="keyword">then</span> next <span class="literal">None</span></span><br><span class="line"> <span class="keyword">else</span> </span><br><span class="line"> <span class="keyword">let</span> child <span class="operator">=</span> c.AddChild()</span><br><span class="line"> <span class="keyword">let</span> successes <span class="operator">=</span> Array.zeroCreate remaining</span><br><span class="line"> <span class="keyword">let</span> <span class="keyword">mutable</span> remaining <span class="operator">=</span> Array.length fibs</span><br><span class="line"> fibers <span class="operator">|></span> Array.iteri (<span class="keyword">fun</span> idx (Fiber call) <span class="operator">-></span></span><br><span class="line"> s.Schedule (<span class="keyword">fun</span> () <span class="operator">-></span> <span class="comment">(* to be defined *)</span>)</span><br><span class="line"> )</span><br></pre></td></tr></table></figure> - <p>Here, we create a dedicated cancellation token, an array of results and a countdown counter - we’re going to decrement it every time one of our fibers completes to know when we’re ready to return a complete result. I’ve left a placeholder for a lambda body that we actually want to schedule. We’re going to fill it right away:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="comment">// defined above: s.Schedule <| fun () -></span></span><br><span class="line">call (s, child) (<span class="keyword">fun</span> result <span class="operator">-></span> </span><br><span class="line"><span class="keyword">match</span> result <span class="keyword">with</span></span><br><span class="line"><span class="operator">|</span> <span class="literal">Some</span> (<span class="literal">Ok</span> success) <span class="operator">-></span></span><br><span class="line"> <span class="comment">// fill the result array</span></span><br><span class="line"> successes.[idx] <span class="operator"><-</span> success</span><br><span class="line"> <span class="keyword">if</span> c.Cancelled <span class="operator">&&</span> Interlocked.Exchange(<span class="operator">&</span>remaining, <span class="number">-1</span>) <span class="operator">></span> <span class="number">0</span> <span class="keyword">then</span></span><br><span class="line"> next <span class="literal">None</span></span><br><span class="line"> <span class="keyword">elif</span> Interlocked.Decrement(<span class="operator">&</span>remaining) <span class="operator">=</span> <span class="number">0</span> <span class="keyword">then</span></span><br><span class="line"> <span class="comment">// if all results have been returned, call the `next` callback</span></span><br><span class="line"> <span class="keyword">if</span> c.Cancelled <span class="keyword">then</span> next <span class="literal">None</span></span><br><span class="line"> <span class="keyword">else</span> next (<span class="literal">Some</span> (<span class="literal">Ok</span> successes))</span><br><span class="line"><span class="operator">|</span> <span class="literal">Some</span> (<span class="literal">Error</span> fail) <span class="operator">-></span></span><br><span class="line"> <span class="keyword">if</span> Interlocked.Exchange(<span class="operator">&</span>remaining, <span class="number">-1</span>) <span class="operator">></span> <span class="number">0</span> <span class="keyword">then</span> </span><br><span class="line"> child.Cancel() <span class="comment">// we failed, cancel other fibers</span></span><br><span class="line"> <span class="keyword">if</span> c.Cancelled <span class="keyword">then</span> next <span class="literal">None</span></span><br><span class="line"> <span class="keyword">else</span> next (<span class="literal">Some</span> (<span class="literal">Error</span> fail))</span><br><span class="line"><span class="operator">|</span> <span class="literal">None</span> <span class="operator">-></span></span><br><span class="line"> <span class="keyword">if</span> Interlocked.Exchange(<span class="operator">&</span>remaining, <span class="number">-1</span>) <span class="operator">></span> <span class="number">0</span> <span class="keyword">then</span> next <span class="literal">None</span>)</span><br></pre></td></tr></table></figure> - <p>As you probably noticed, we’re using <code>Interlocked</code> class again - that’s because now we have multiple fibers running in parallel, therefore our access to shared mutable values is not thread safe. This includes <code>remaining</code> counter decrement operation. This however doesn’t apply to <code>successes.[i] <- success</code> - since every fiber knows and touches only its own index within result array, there’s no worry that any other will try to push its result in the same place.</p> -<p>What you also can see, we’re using a <code>-1</code> here as a magic value - we’ll use it on the counter as a flag to determine if any of the fibers failed/was cancelled - and if so, which one of them will call the <code>next</code> callback.</p> -<h4 id="Racing-to-completion"><a href="#Racing-to-completion" class="headerlink" title="Racing to completion"></a>Racing to completion</h4><p>With first operator (<code>Fiber.parallel</code>) ready, now it’s the time to implement <code>Fiber.race</code>. Since I’ve discussed it behavior multiple times in this post already, let’s dive straight into the code:</p> +<p>What you also can see, we’re using a <code>-1</code> here as a magic value - we’ll use it on the counter as a flag to determine if any of the fibers failed/was cancelled - and if so, which one of them will call the <code>next</code> callback.</p> +<h4 id="Racing-to-completion"><a class="header-anchor" href="#Racing-to-completion">¶</a>Racing to completion</h4> +<p>With first operator (<code>Fiber.parallel</code>) ready, now it’s the time to implement <code>Fiber.race</code>. Since I’ve discussed it behavior multiple times in this post already, let’s dive straight into the code:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> race (Fiber left) (Fiber right)<span class="operator">:</span> Fiber<span class="operator"><</span>Choice<span class="operator"><</span><span class="symbol">'a</span>, <span class="symbol">'b</span><span class="operator">>></span> <span class="operator">=</span></span><br><span class="line"> Fiber <span class="operator"><|</span> <span class="keyword">fun</span> (s, c) next <span class="operator">-></span></span><br><span class="line"> <span class="keyword">if</span> c.Cancelled <span class="keyword">then</span> next <span class="literal">None</span></span><br><span class="line"> <span class="keyword">else</span> </span><br><span class="line"> <span class="keyword">let</span> <span class="keyword">mutable</span> flag <span class="operator">=</span> <span class="number">0</span></span><br><span class="line"> <span class="keyword">let</span> cancelChild <span class="operator">=</span> c.AddChild()</span><br><span class="line"> <span class="keyword">let</span> run fiber choice <span class="operator">=</span></span><br><span class="line"> <span class="comment">(* to be described *)</span></span><br><span class="line"> run left Choice1Of2</span><br><span class="line"> run right Choice2Of2</span><br></pre></td></tr></table></figure> - <p>So again, we want to have shared mutable flag, which we’ll use to determine, which of the fibers finished as a first one to be able to call fiber’s callback safely and cancel the other. You may see, that our returned fiber uses <code>Choice<,></code> type - this means, that our left and right fibers can have results of different types. We’ll use that soon, but first we need to complete our <code>run</code> function body:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> run fiber choice <span class="operator">=</span></span><br><span class="line"> s.Schedule (<span class="keyword">fun</span> () <span class="operator">-></span></span><br><span class="line"> fiber (s, cancelChild) (<span class="keyword">fun</span> result <span class="operator">-></span></span><br><span class="line"> <span class="keyword">if</span> Interlocked.Exchange(<span class="operator">&</span>flag, <span class="number">1</span>) <span class="operator">=</span> <span class="number">0</span> <span class="keyword">then</span></span><br><span class="line"> cancelChild.Cancel()</span><br><span class="line"> <span class="keyword">if</span> c.Cancelled <span class="keyword">then</span> next <span class="literal">None</span></span><br><span class="line"> <span class="keyword">else</span> <span class="keyword">match</span> result <span class="keyword">with</span></span><br><span class="line"> <span class="operator">|</span> <span class="literal">None</span> <span class="operator">-></span> next <span class="literal">None</span></span><br><span class="line"> <span class="operator">|</span> <span class="literal">Some</span>(<span class="literal">Ok</span> v) <span class="operator">-></span> next (<span class="literal">Some</span>(<span class="literal">Ok</span>(choice v)))</span><br><span class="line"> <span class="operator">|</span> <span class="literal">Some</span>(<span class="literal">Error</span> e) <span class="operator">-></span> next (<span class="literal">Some</span>(<span class="literal">Error</span> e))))</span><br></pre></td></tr></table></figure> - <p>What we do here is simply trying to race to “reserve” out flag variable - the winner gets his result mapped to corresponding choice, while looser gets cancelled.</p> <p>What’s interesting, we can now combine our <code>race</code> and <code>delay</code> functions to easily implement timeout mechanism:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> timeout (t<span class="operator">:</span> TimeSpan) fiber <span class="operator">=</span></span><br><span class="line"> Fiber <span class="operator"><|</span> <span class="keyword">fun</span> (s, c) next <span class="operator">-></span></span><br><span class="line"> <span class="keyword">let</span> (Fiber call) <span class="operator">=</span> race (delay t) fiber</span><br><span class="line"> call (s, c) (<span class="keyword">fun</span> result <span class="operator">-></span></span><br><span class="line"> <span class="keyword">if</span> c.Cancelled <span class="keyword">then</span> next <span class="literal">None</span></span><br><span class="line"> <span class="keyword">else</span> <span class="keyword">match</span> result <span class="keyword">with</span></span><br><span class="line"> <span class="operator">|</span> <span class="literal">None</span> <span class="operator">-></span> next <span class="literal">None</span></span><br><span class="line"> <span class="operator">|</span> <span class="literal">Some</span>(<span class="literal">Ok</span> (Choice1Of2 _)) <span class="operator">-></span> next <span class="literal">None</span> <span class="comment">// timeout won</span></span><br><span class="line"> <span class="operator">|</span> <span class="literal">Some</span>(<span class="literal">Ok</span> (Choice2Of2 v)) <span class="operator">-></span> next (<span class="literal">Some</span>(<span class="literal">Ok</span> v))</span><br><span class="line"> <span class="operator">|</span> <span class="literal">Some</span>(<span class="literal">Error</span> e) <span class="operator">-></span> next (<span class="literal">Some</span>(<span class="literal">Error</span> e))</span><br><span class="line"> )</span><br></pre></td></tr></table></figure> - <p>The one last thing left for us, is to be able to run out fibers on the main thread - otherwise we’d start our program, schedule fibers to run in the background and then close the program without waiting for the results.</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> blocking (s<span class="operator">:</span> IScheduler) (cancel<span class="operator">:</span> Cancel) (Fiber fn) <span class="operator">=</span></span><br><span class="line"> <span class="keyword">use</span> waiter <span class="operator">=</span> <span class="keyword">new</span> ManualResetEventSlim(<span class="literal">false</span>)</span><br><span class="line"> <span class="keyword">let</span> <span class="keyword">mutable</span> res <span class="operator">=</span> <span class="literal">None</span></span><br><span class="line"> s.Schedule(<span class="keyword">fun</span> () <span class="operator">-></span> fn (s, cancel) (<span class="keyword">fun</span> result <span class="operator">-></span></span><br><span class="line"> <span class="keyword">if</span> <span class="built_in">not</span> cancel.Cancelled <span class="keyword">then</span></span><br><span class="line"> Interlocked.Exchange(<span class="operator">&</span>res, <span class="literal">Some</span> result) <span class="operator">|></span> <span class="built_in">ignore</span></span><br><span class="line"> waiter.Set()))</span><br><span class="line"> waiter.Wait()</span><br><span class="line"> res.Value</span><br></pre></td></tr></table></figure> - <p>It’s simple - we’ll use standard synchronization primitives provided by .NET runtime, to hold current OS thread until we complete. Sure it’s blocking an OS thread, but we’ll eventually need that if we don’t want our program’s main function to finish before all fibers inside the thread pool complete.</p> -<h3 id="Simulating-real-environment-in-tests"><a href="#Simulating-real-environment-in-tests" class="headerlink" title="Simulating real environment in tests"></a>Simulating real environment in tests</h3><p>In theory, we could be done here. But, if you managed to read up to this point, we may want to cover one last scenario. Imagine that we’d want to test our fibers. However running tests using standard thread pool scheduler can lead to funky issues:</p> +<h3 id="Simulating-real-environment-in-tests"><a class="header-anchor" href="#Simulating-real-environment-in-tests">¶</a>Simulating real environment in tests</h3> +<p>In theory, we could be done here. But, if you managed to read up to this point, we may want to cover one last scenario. Imagine that we’d want to test our fibers. However running tests using standard thread pool scheduler can lead to funky issues:</p> <ul> <li>Sometimes you may trigger some race conditions in your code, that only happen in specific situations (like high CPU contention) and are almost impossible to reproduce during debug sessions.</li> -<li>Other times you may have some lengthy delays/timeouts in your code, like waiting for seconds or even minutes before continuing. Guess what: now your test will wait for just as long.</li> +<li>Other times you may have some lengthy delays/timeouts in your code, like waiting for seconds or even minutes before continuing. Guess what: now your test will wait for just as long.</li> </ul> -<p>These are not new problems. They are well known in world of concurrent and distributed systems. What we need, is a simulation of execution environment. If you want to listen more about that concept, I could recommend you <a href="https://www.youtube.com/watch?v=4fFDFbi3toc&ref=bartoszsypytkowski.com">this presentaton</a>. To run our test predictably, we’ll create a dedicated test scheduler, which will run our code in deterministic fashion (on a single core) and in a way that’s detached from other invariants eg. actual physical clock and random number generator.</p> +<p>These are not new problems. They are well known in world of concurrent and distributed systems. What we need, is a simulation of execution environment. If you want to listen more about that concept, I could recommend you <a href="https://www.youtube.com/watch?v=4fFDFbi3toc&ref=bartoszsypytkowski.com">this presentaton</a>. To run our test predictably, we’ll create a dedicated test scheduler, which will run our code in deterministic fashion (on a single core) and in a way that’s detached from other invariants eg. actual physical clock and random number generator.</p> <p>The idea here is simple - our scheduler will operate on notion of virtual timeline. When we’ll try to schedule a new function - to trigger either immediately or after some timeout - we’ll store it inside an ordered collection, a timeline. Some of the technical decisions we also made for purposes of this implementation:</p> <ul> <li>Whenever a fiber is going to schedule multiple parallel executions “at the same time”, we’ll put them all into a single bucket on a timeline. Later on I’ll cover, why this is useful.</li> @@ -479,20 +463,16 @@ </ul> <p>After describing the concept behind the algorithm, the actual implementation really shouldn’t be that surprising:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">type</span> <span class="title class_">TestScheduler</span>(now<span class="operator">:</span> DateTime) <span class="operator">=</span></span><br><span class="line"> <span class="keyword">let</span> <span class="keyword">mutable</span> running <span class="operator">=</span> <span class="literal">false</span></span><br><span class="line"> <span class="keyword">let</span> <span class="keyword">mutable</span> currentTime <span class="operator">=</span> now.Ticks</span><br><span class="line"> <span class="keyword">let</span> <span class="keyword">mutable</span> timeline <span class="operator">=</span> Map.empty</span><br><span class="line"> <span class="keyword">let</span> schedule delay fn <span class="operator">=</span> <span class="comment">(* to be defined *)</span></span><br><span class="line"> <span class="keyword">let</span> <span class="keyword">rec</span> run () <span class="operator">=</span> <span class="comment">(* to be defined *)</span></span><br><span class="line"> <span class="keyword">interface</span> IScheduler <span class="keyword">with</span></span><br><span class="line"> <span class="keyword">member</span> this.Schedule fn <span class="operator">=</span> </span><br><span class="line"> schedule <span class="number">0</span>L fn</span><br><span class="line"> <span class="keyword">if</span> <span class="built_in">not</span> running <span class="keyword">then</span></span><br><span class="line"> running <span class="operator"><-</span> <span class="literal">true</span></span><br><span class="line"> run ()</span><br><span class="line"> <span class="keyword">member</span> this.Delay (timeout<span class="operator">:</span> TimeSpan, fn) <span class="operator">=</span> schedule timeout.Ticks fn</span><br></pre></td></tr></table></figure> - <p>We’re using a <code>running</code> flag here to not try to invoke <code>run</code> multiple times in nested manner - this would cause non-tailable recursion and potential stack overflow in more expensive tests.</p> <p>The schedule function is pretty simple - calculate expected execution time for a function, then add that function to be executed at that point in time.</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> schedule delay fn <span class="operator">=</span> </span><br><span class="line"> <span class="keyword">let</span> at <span class="operator">=</span> currentTime <span class="operator">+</span> delay</span><br><span class="line"> timeline <span class="operator"><-</span></span><br><span class="line"> <span class="keyword">match</span> Map.tryFind at timeline <span class="keyword">with</span></span><br><span class="line"> <span class="operator">|</span> <span class="literal">None</span> <span class="operator">-></span> Map.add at [fn] timeline </span><br><span class="line"> <span class="operator">|</span> <span class="literal">Some</span> fns <span class="operator">-></span> Map.add at (fn<span class="operator">::</span>fns) timeline</span><br></pre></td></tr></table></figure> - <p>Given all of the code we already survived in this blog post, run loop should be pretty simple:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> <span class="keyword">rec</span> run () <span class="operator">=</span></span><br><span class="line"> <span class="keyword">match</span> Seq.tryHead timeline <span class="keyword">with</span></span><br><span class="line"> <span class="operator">|</span> <span class="literal">None</span> <span class="operator">-></span> running <span class="operator"><-</span> <span class="literal">false</span></span><br><span class="line"> <span class="operator">|</span> <span class="literal">Some</span> (KeyValue(time, bucket)) <span class="operator">-></span></span><br><span class="line"> timeline <span class="operator"><-</span> Map.remove time timeline</span><br><span class="line"> currentTime <span class="operator"><-</span> time</span><br><span class="line"> <span class="keyword">for</span> fn <span class="keyword">in</span> List.rev bucket <span class="keyword">do</span> </span><br><span class="line"> fn () </span><br><span class="line"> run ()</span><br></pre></td></tr></table></figure> - <p>We’ll try to pick the first entry from the timeline - since here we use F# map, which is sorted in ascending order, we know that first entry is the one with the shortest execution timeout. We update our “current” time to match the expected one we calculated earlier, and finally we execute all functions scheduled at that time and repeat the loop all over until we eventually run out of scheduled actions.</p> <p>Now here’s the trick - we use <code>List.rev</code> to execute functions in the same order in which they were scheduled, because we want our tests to be deterministic and our bugs to be reproducible. However this is not the only strategy - since we know that functions in the same bucket could as well be executing in parallel, we could shuffle them around in different permutations for early discovery of some data races! I’ll won’t dive into it, but leave that idea as food for thoughts for you.</p> <p>One last note about the test scheduler is that isolating it from the actual physical clock means, we cannot trust our time functions (like <code>DateTime.UtcNow</code>) any longer. This shouldn’t really be an issue though - because relying on physical time would potentially make our tests indeterministic, we didn’t want to use it anyway, right?</p> <p>However, we need to be able to obtain current time from the scheduler, so we need to extend its API:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">type</span> <span class="title class_">IScheduler</span> <span class="operator">=</span></span><br><span class="line"> <span class="keyword">abstract</span> UtcNow<span class="operator">:</span> <span class="type">unit</span> <span class="operator">-></span> <span class="type">unit</span></span><br><span class="line"> <span class="comment">// ... other methods</span></span><br><span class="line"> </span><br><span class="line"><span class="keyword">type</span> <span class="title class_">TestScheduler</span>() <span class="operator">=</span></span><br><span class="line"> <span class="keyword">let</span> <span class="keyword">mutable</span> currentTime <span class="operator">=</span> DateTime.UtcNow.Ticks</span><br><span class="line"> <span class="comment">// ... rest of the implementation</span></span><br><span class="line"> <span class="keyword">interface</span> IScheduler <span class="keyword">with</span></span><br><span class="line"> <span class="keyword">member</span> __.UtcNow() <span class="operator">=</span> DateTime(currentTime)</span><br><span class="line"> <span class="comment">// ... other methods</span></span><br></pre></td></tr></table></figure> - <p>And that’s all. As always, if you got confused or have a problems along the way, you can get the entire code <a href="https://gist.github.com/Horusiath/9c790691130150b524aaa9ab426ed982?ref=bartoszsypytkowski.com">here</a>. I wanted to thank to Anthony Lloyd for his initial work on porting Scala <a href="https://zio.dev/?ref=bartoszsypytkowski.com">ZIO</a> library to F#, which brought me an inspiration to write this piece.</p> ]]></content> <tags> @@ -520,7 +500,6 @@ </ol> <p>假设正在开发一个电子商务系统,业务专家使用“订单”来描述用户购买的商品集合。团队可以在代码中使用“Order”来命名相关的类和方法:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">type</span> <span class="title class_">Order</span> <span class="operator">=</span> {</span><br><span class="line"> items<span class="operator">:</span> OrderItem <span class="type">list</span></span><br><span class="line"> customer<span class="operator">:</span> Customer</span><br><span class="line"> orderDate<span class="operator">:</span> DateTime</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">OrderItem</span> <span class="operator">=</span> {</span><br><span class="line"> product<span class="operator">:</span> Product</span><br><span class="line"> quantity<span class="operator">:</span> <span class="type">int</span></span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">Customer</span> <span class="operator">=</span> {</span><br><span class="line"> name<span class="operator">:</span> <span class="type">string</span></span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">Product</span> <span class="operator">=</span> {</span><br><span class="line"> name<span class="operator">:</span> <span class="type">string</span></span><br><span class="line"> price<span class="operator">:</span> <span class="type">float</span></span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> addItem (order<span class="operator">:</span> Order) (item<span class="operator">:</span> OrderItem) <span class="operator">=</span></span><br><span class="line"> { order <span class="keyword">with</span> items <span class="operator">=</span> order.items <span class="operator">@</span> [item] }</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> getTotalAmount (order<span class="operator">:</span> Order) <span class="operator">=</span></span><br><span class="line"> <span class="keyword">let</span> total <span class="operator">=</span> <span class="number">0.0</span></span><br><span class="line"> <span class="keyword">for</span> item <span class="keyword">in</span> order.items <span class="keyword">do</span></span><br><span class="line"> total <span class="operator"><-</span> total <span class="operator">+</span> item.price</span><br><span class="line"> total</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> getPrice (item<span class="operator">:</span> OrderItem) <span class="operator">=</span></span><br><span class="line"> item.product.price <span class="operator">*</span> item.quantity</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> getTotalPrice (order<span class="operator">:</span> Order) <span class="operator">=</span></span><br><span class="line"> <span class="keyword">let</span> total <span class="operator">=</span> <span class="number">0.0</span></span><br><span class="line"> <span class="keyword">for</span> item <span class="keyword">in</span> order.items <span class="keyword">do</span></span><br><span class="line"> total <span class="operator"><-</span> total <span class="operator">+</span> getPrice(item)</span><br><span class="line"> total</span><br></pre></td></tr></table></figure> - <p>在这个示例中使用了“Order”、“OrderItem”、“Customer”和“Product”等术语,这些术语都是 Ubiquitous Language 的一部分,可以提高代码与业务需求的一致性。</p> ]]></content> <tags> @@ -535,48 +514,44 @@ <p>On the other side in functional space, there’s no one opinionated solution or approach - various things have been proposed, usually depending on features that languages and compiler have to offer. And since pretty much all functional languages offer this thing known as partial application, for many years it was the most common answer for the problem of managing dependencies.</p> <p>In short we’re talking about dependency injection by function parameter, like:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="comment">// foo requires 2 dependencies to serve the incoming request</span></span><br><span class="line"><span class="keyword">let</span> foo bar baz request <span class="operator">=</span> <span class="operator">???</span></span><br><span class="line"><span class="comment">// we're providing dependencies by partial application</span></span><br><span class="line"><span class="keyword">let</span> wired <span class="operator">=</span> foo dependency1 dependency2</span><br><span class="line"><span class="comment">// now wired can serve request directly without calling </span></span><br><span class="line"><span class="comment">// dependencies every time</span></span><br><span class="line"><span class="keyword">let</span> response <span class="operator">=</span> wired request</span><br></pre></td></tr></table></figure> - -<p>It’s very simple, doesn’t require reflection or dedicated library. However there are several pain points coming with this approach - visible especially as our code base grows and become more complex. However latest approaches popularized by libraries like Scala <a href="https://zio.dev/?ref=bartoszsypytkowski.com">ZIO</a> or Haskell’s <a href="https://youtu.be/idU7GdlfP9Q?t=1394&ref=bartoszsypytkowski.com">Polysemy</a> challenge this approach.</p> -<h2 id="Partial-application"><a href="#Partial-application" class="headerlink" title="Partial application"></a>Partial application</h2><p>There are some design decisions, when partial application doesn’t always give a clear answer. Example:</p> +<p>It’s very simple, doesn’t require reflection or dedicated library. However there are several pain points coming with this approach - visible especially as our code base grows and become more complex. However latest approaches popularized by libraries like Scala <a href="https://zio.dev/?ref=bartoszsypytkowski.com">ZIO</a> or Haskell’s <a href="https://youtu.be/idU7GdlfP9Q?t=1394&ref=bartoszsypytkowski.com">Polysemy</a> challenge this approach.</p> +<h2 id="Partial-application"><a class="header-anchor" href="#Partial-application">¶</a>Partial application</h2> +<p>There are some design decisions, when partial application doesn’t always give a clear answer. Example:</p> <blockquote> -<p>Imagine using a set of methods, that are closely related and - in object oriented world - encapsulated within a single object, like database query/execute or different logging methods (debug/info/warning/error).</p> +<p>Imagine using a set of methods, that are closely related and - in object oriented world - encapsulated within a single object, like database query/execute or different logging methods (debug/info/warning/error).</p> </blockquote> <p>Now, given that our function needs to use potentially more than one of these, how should we pass our arguments?:</p> <ol> <li>Functional purist path - pass every dependency as a separate function parameter: <code>let doSmth logError logInfo = ??</code>. While it allows us to precisely describe what this function uses, it would of course lead to explosion of function parameters. Additionally every time you need new function in your existing code, you need to partially apply it at all call sites.</li> <li>Describe operations using ADT (algebraic data types) and inject a function that will work as an interpreter for them: <code>let doSmth (log: LogEvent -> unit) = ??</code>. While it’s easy to mock (you don’t need to implement everything, only pattern match on cases that matter for a particular test) and reduces params affinity, it also comes with a lot of indirection, that may lead to harder to grasp, especially during debugging. Sometimes a performance penalty is also to be expected.</li> -<li>Fallback to objects/interfaces and pass them as methods: <code>let doSmth (logger: ILogger) = ??</code>. While interfaces may simplify dependency tree, it’s not always obvious when to use it. Mocking story is also more painful + interfaces are not inferred by F# compiler.</li> +<li>Fallback to objects/interfaces and pass them as methods: <code>let doSmth (logger: ILogger) = ??</code>. While interfaces may simplify dependency tree, it’s not always obvious when to use it. Mocking story is also more painful + interfaces are not inferred by F# compiler.</li> </ol> <p>These are quite common options I’ve seen in the wild - each having their own advantages and disadvantages. Which one to use? Good question, as in practice with codebases that are old enough, you usually see 2 or even all 3 of them mixed together. This can lead to some confusion and obscurity over time.</p> <p>What’s worse, none of these cases really solves problem of dependency management - all they do is just try to reduce it to a manageable scope. Eventually you’ll end up manually wiring - by partial application - dozens of functions and managing all of the dependencies between them by hand.</p> -<h3 id="Example"><a href="#Example" class="headerlink" title="Example"></a>Example</h3><p>In order to get better understanding, we’ll use a fairly simple example - changing user password:</p> +<h3 id="Example"><a class="header-anchor" href="#Example">¶</a>Example</h3> +<p>In order to get better understanding, we’ll use a fairly simple example - changing user password:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> fetchUser (db<span class="operator">:</span> IDbConnection) userId <span class="operator">=</span> </span><br><span class="line"> db.QueryFirstAsync(Sql.FetchUser, {<span class="operator">|</span> userId <span class="operator">=</span> userid<span class="operator">|</span> })</span><br><span class="line"> </span><br><span class="line"><span class="keyword">let</span> updateUser (db<span class="operator">:</span> IDbConnection) user <span class="operator">=</span> db.ExecuteAsync(Sql.UpdateUser, user)</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> changePass (logger<span class="operator">:</span> ILogger) fetch update <span class="operator">=</span> <span class="keyword">fun</span> req <span class="operator">-></span> <span class="keyword">task</span> {</span><br><span class="line"> <span class="keyword">let!</span> user <span class="operator">=</span> fetch req.UserId</span><br><span class="line"> <span class="keyword">if</span> user.Hash <span class="operator">=</span> bcrypt user.Salt req.OldPass <span class="keyword">then</span></span><br><span class="line"> <span class="keyword">let</span> salt <span class="operator">=</span> generateSalt ()</span><br><span class="line"> <span class="keyword">let</span> user' <span class="operator">=</span> { user <span class="keyword">with</span> Salt <span class="operator">=</span> salt; Hash <span class="operator">=</span> bcrypt salt req.NewPass }</span><br><span class="line"> <span class="keyword">do!</span> update user'</span><br><span class="line"> logger.LogInformation <span class="string">"Password change: user %i"</span> user.Id</span><br><span class="line"> <span class="keyword">return</span> <span class="literal">Ok</span> ()</span><br><span class="line"> <span class="keyword">else</span> </span><br><span class="line"> logger.LogError <span class="string">"Password change unauthorized: user %i"</span> user.Id</span><br><span class="line"> <span class="keyword">return</span> <span class="literal">Error</span> <span class="string">"Old password is invalid"</span></span><br><span class="line">}</span><br><span class="line"></span><br></pre></td></tr></table></figure> - <p>Here we have a fairly short snippet with some dependencies? But how many in practice?:</p> <ul> -<li>Number of parameters suggest 3, but depending on our choices it could be 4 (if we decide to pass log error and info separately) or 2 (if we conflate fetch/update into dedicated interface).</li> +<li>Number of parameters suggest 3, but depending on our choices it could be 4 (if we decide to pass log error and info separately) or 2 (if we conflate fetch/update into dedicated interface).</li> <li>It’s not hard to imagine that in the future our <code>bcrypt</code> hashing function may turn out to be configurable - maybe even per each user. That may need a configurable parameter.</li> <li>Maybe aside of the logger we may be needing a separate telemetry mechanism to count number of incoming request or password validation failures? That means another parameter.</li> <li>Salt generation is pseudo-random process - it we want our function to be deterministic, we should probably parametrize it over explicitly passed <code>Random</code> as well.</li> </ul> <p>As you see, what seemed to be simple task at the beginning can quickly blow up out of proportion. As the number of arguments grows, the more nasty our wiring code eventually becomes. Quite common pattern is to hide all of that nastiness under the carpet a.k.a. composition root. However this doesn’t have to be the case.</p> <p>Below we’ll cover another approach for dealing with dependencies - inspired by Scala <a href="https://medium.com/@pascal.mengelt/what-are-the-benefits-of-the-zio-modules-with-zlayers-3bf6cc064a9b?ref=bartoszsypytkowski.com">ZIO</a> library - using incremental steps, from first principles to monadic bindings.</p> -<h2 id="Managing-dependencies-beyond-partial-application"><a href="#Managing-dependencies-beyond-partial-application" class="headerlink" title="Managing dependencies beyond partial application"></a>Managing dependencies beyond partial application</h2><p>Let’s start from how our code from above will eventually look like at the end of this step:</p> +<h2 id="Managing-dependencies-beyond-partial-application"><a class="header-anchor" href="#Managing-dependencies-beyond-partial-application">¶</a>Managing dependencies beyond partial application</h2> +<p>Let’s start from how our code from above will eventually look like at the end of this step:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> changePass env <span class="operator">=</span> <span class="keyword">fun</span> req <span class="operator">-></span> <span class="keyword">task</span> {</span><br><span class="line"> <span class="keyword">let!</span> user <span class="operator">=</span> Db.fetchUser env req.UserId</span><br><span class="line"> <span class="keyword">if</span> user.Hash <span class="operator">=</span> bcrypt user.Salt req.OldPass <span class="keyword">then</span></span><br><span class="line"> <span class="keyword">let</span> salt <span class="operator">=</span> Random.bytes env <span class="number">32</span></span><br><span class="line"> <span class="keyword">do!</span> Db.updateUser <span class="keyword">env</span> { user <span class="keyword">with</span> Salt <span class="operator">=</span> salt; Hash <span class="operator">=</span> bcrypt salt req.NewPass }</span><br><span class="line"> Log.info env <span class="string">"Changed password for user %i"</span> user.Id</span><br><span class="line"> <span class="keyword">return</span> <span class="literal">Ok</span> ()</span><br><span class="line"> <span class="keyword">else</span> </span><br><span class="line"> Log.error env <span class="string">"Password change unauthorized: user %i"</span> user.Id</span><br><span class="line"> <span class="keyword">return</span> <span class="literal">Error</span> <span class="string">"Old password is invalid"</span></span><br><span class="line">}</span><br></pre></td></tr></table></figure> - -<p>As you may notice, all of our partially applied parameters disappeared, replaced by some single cryptic <code>env</code> parameter. We’ll get there soon. We also packed similar capabilities into corresponding modules (<code>Db</code>/<code>Log</code>/<code>Random</code>). Lets start from defining them:</p> +<p>As you may notice, all of our partially applied parameters disappeared, replaced by some single cryptic <code>env</code> parameter. We’ll get there soon. We also packed similar capabilities into corresponding modules (<code>Db</code>/<code>Log</code>/<code>Random</code>). Lets start from defining them:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="meta">[<Interface>]</span></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">ILogger</span> <span class="operator">=</span></span><br><span class="line"> <span class="keyword">abstract</span> Debug<span class="operator">:</span> <span class="type">string</span> <span class="operator">-></span> <span class="type">unit</span></span><br><span class="line"> <span class="keyword">abstract</span> <span class="literal">Error</span><span class="operator">:</span> <span class="type">string</span> <span class="operator">-></span> <span class="type">unit</span> </span><br><span class="line"></span><br><span class="line"><span class="meta">[<Interface>]</span> <span class="keyword">type</span> <span class="title class_">ILog</span> <span class="operator">=</span> <span class="keyword">abstract</span> Logger<span class="operator">:</span> ILogger</span><br><span class="line"></span><br><span class="line"><span class="keyword">module</span> Log <span class="operator">=</span></span><br><span class="line"> <span class="keyword">let</span> debug (env<span class="operator">:</span> #ILog) fmt <span class="operator">=</span> Printf.kprintf env.Logger.Debug fmt</span><br><span class="line"> <span class="keyword">let</span> error (env<span class="operator">:</span> #ILog) fmt <span class="operator">=</span> Printf.kprintf env.Logger.<span class="literal">Error</span> fmt</span><br></pre></td></tr></table></figure> - <p>Now we can say something more about <code>env</code>. The secret is in <code>#ILog</code> signature, which means that our environment can be any generic type implementing <code>ILog</code> interface. As soon you’ll see, this approach is highly composable, but before that we’ll need another module:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="meta">[<Interface>]</span></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">IDatabase</span> <span class="operator">=</span></span><br><span class="line"> <span class="keyword">abstract</span> Query<span class="operator">:</span> <span class="type">string</span> <span class="operator">*</span> <span class="symbol">'i</span> <span class="operator">-></span> Task<span class="operator"><</span><span class="symbol">'o</span><span class="operator">></span></span><br><span class="line"> <span class="keyword">abstract</span> Execute<span class="operator">:</span> <span class="type">string</span> <span class="operator">*</span> <span class="symbol">'i</span> <span class="operator">-></span> Task</span><br><span class="line"> </span><br><span class="line"><span class="meta">[<Interface>]</span> <span class="keyword">type</span> <span class="title class_">IDb</span> <span class="operator">=</span> <span class="keyword">abstract</span> Database<span class="operator">:</span> IDatabase</span><br><span class="line"></span><br><span class="line"><span class="keyword">module</span> Db <span class="operator">=</span> </span><br><span class="line"> <span class="keyword">let</span> fetchUser (env<span class="operator">:</span> #IDb) userId <span class="operator">=</span> </span><br><span class="line"> env.Database.Query(Sql.FetchUser, {<span class="operator">|</span> userId <span class="operator">=</span> userId <span class="operator">|</span>})</span><br><span class="line"> <span class="keyword">let</span> updateUser (env<span class="operator">:</span> #IDb) user <span class="operator">=</span> env.Database.Execute(Sql.UpdateUser, user)</span><br></pre></td></tr></table></figure> - <p>Now what will happen if we use functions from both <code>Log</code> and <code>Db</code> modules? As it turns out, F# compiler can properly infer generic constraints over these interfaces. The result <code>env</code> type constraint is inferred to be an union - just like set union, which also means that it handles duplicates for us - of all constraints of other functions using <code>env</code> in its scope:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> foo env <span class="operator">=</span> <span class="comment">// env :> IDb and env :> ILog</span></span><br><span class="line"> <span class="keyword">let</span> user <span class="operator">=</span> Db.fetchUser env <span class="number">123</span> <span class="comment">// env :> IDb</span></span><br><span class="line"> Log.debug env <span class="string">"User: %A"</span> user <span class="comment">// env :> ILog</span></span><br></pre></td></tr></table></figure> - -<p>Now why did we use two separate interfaces (<code>ILog</code>/<code>ILogger</code>) instead of making environment implement <code>ILogger</code> directly? This is more practical approach that will let us isolate capabilities of particular modules rather than putting them flat into our environment. Example:</p> +<p>Now why did we use two separate interfaces (<code>ILog</code>/<code>ILogger</code>) instead of making environment implement <code>ILogger</code> directly? This is more practical approach that will let us isolate capabilities of particular modules rather than putting them flat into our environment. Example:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">module</span> Log <span class="operator">=</span></span><br><span class="line"> <span class="keyword">let</span> live <span class="operator">:</span> ILogger <span class="operator">=</span> <span class="operator">??</span> <span class="comment">// create logger interface</span></span><br><span class="line"></span><br><span class="line"><span class="meta">[<Struct>]</span></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">AppEnv</span> <span class="operator">=</span> </span><br><span class="line"> <span class="keyword">interface</span> ILog <span class="keyword">with</span> <span class="keyword">member</span> _.Logger <span class="operator">=</span> Log.live</span><br><span class="line"> <span class="keyword">interface</span> IDb <span class="keyword">with</span> <span class="keyword">member</span> _.Database <span class="operator">=</span> Db.live connectionString</span><br><span class="line"> </span><br><span class="line">foo (AppEnv())</span><br></pre></td></tr></table></figure> - -<p>We cannot eagerly provide a specific implementation of <code>ILog</code>/<code>IDb</code>, because they’re yet to be defined as part of by our environment type (which may need to implement many interfaces). To maintain module encapsulation <code>Log</code> module shouldn’t be aware of existence or implementation of <code>IDb</code> interface and vice versa for <code>Db</code> module. What we can do however is to provide <code>live</code> implementation of <code>ILogger</code>, which encapsulates capabilities required by the <code>Log</code> module. This way we don’t need to know details of <code>ILogger</code> when defining our environment type.</p> +<p>We cannot eagerly provide a specific implementation of <code>ILog</code>/<code>IDb</code>, because they’re yet to be defined as part of by our environment type (which may need to implement many interfaces). To maintain module encapsulation <code>Log</code> module shouldn’t be aware of existence or implementation of <code>IDb</code> interface and vice versa for <code>Db</code> module. What we can do however is to provide <code>live</code> implementation of <code>ILogger</code>, which encapsulates capabilities required by the <code>Log</code> module. This way we don’t need to know details of <code>ILogger</code> when defining our environment type.</p> <p>Strong sides of this approach?:</p> <ul> <li>We only need to provide a single environment object instead of (potentially) unbounded list of parameters. Since it’s always one, it’s easier to generalize and compose other functions over it.</li> @@ -587,12 +562,12 @@ <li>It doesn’t impose specific restrictions on libraries and frameworks.</li> </ul> <p>Now we could as well stop here - IMHO this approach is already good and useful for most cases. We can also try to push it further. As you’ve seen, our code now requires quite a lot of <code>env</code> passing around. Could we do something about this? It turns out that yes, we could.</p> -<h2 id="Reader-monad"><a href="#Reader-monad" class="headerlink" title="Reader monad"></a>Reader monad</h2><p>Before we continue: what we’re going to cover now is less useful in terms of current state of F# ecosystem for the reasons I’ll mention later.</p> +<h2 id="Reader-monad"><a class="header-anchor" href="#Reader-monad">¶</a>Reader monad</h2> +<p>Before we continue: what we’re going to cover now is less useful in terms of current state of F# ecosystem for the reasons I’ll mention later.</p> <p>The pattern we’ll use here is known as a <a href="https://fsharpforfunandprofit.com/posts/elevated-world-6/?ref=bartoszsypytkowski.com">Reader Monad</a>. While it’s useful in certain situations, it’s not widely used - IMO it’s fault lies in the name itself, which somehow managed to sound both borderline meaningless and scary in ears of many developers.</p> <p>The rest of this blog post will be introduction to this style in F#, however focused solely around problem of dependency management - we’ll ignore other aspects of monads.</p> -<p>We’ll going to reuse our environment type from above, but now encode it directly into another type we’ll call <code>Effect</code>. Since I’ve mentioned that our pattern has M-word in it, you can safely assume that our handler’s logic will be defined as a lazy sequence of steps to be executed (sounds almost like async/await). In F# we’ll sugar them by using custom computation expression (I’m going to call it <code>effect { ... }</code>) returning our effect type, which we’ll define as:</p> +<p>We’ll going to reuse our environment type from above, but now encode it directly into another type we’ll call <code>Effect</code>. Since I’ve mentioned that our pattern has M-word in it, you can safely assume that our handler’s logic will be defined as a lazy sequence of steps to be executed (sounds almost like async/await). In F# we’ll sugar them by using custom computation expression (I’m going to call it <code>effect { ... }</code>) returning our effect type, which we’ll define as:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="meta">[<Struct>]</span> <span class="keyword">type</span> <span class="title class_">Effect</span><span class="operator"><</span><span class="symbol">'env</span>, <span class="symbol">'out</span><span class="operator">></span> <span class="operator">=</span> Effect <span class="keyword">of</span> (<span class="symbol">'env</span> <span class="operator">-></span> <span class="symbol">'out</span>)</span><br></pre></td></tr></table></figure> - <p>Where:</p> <ul> <li><code>env</code> is our environment type we already talked about above.</li> @@ -600,30 +575,25 @@ </ul> <p>Eventually, with this type in hand our simple request handler will be looking like that:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> changePass req <span class="operator">=</span> <span class="keyword">effect</span> {</span><br><span class="line"> <span class="keyword">let!</span> user <span class="operator">=</span> Db.fetchUser req.UserId</span><br><span class="line"> <span class="keyword">if</span> user.Hash <span class="operator">=</span> bcrypt user.Salt req.OldPass <span class="keyword">then</span></span><br><span class="line"> <span class="keyword">let!</span> salt <span class="operator">=</span> Random.bytes <span class="number">32</span></span><br><span class="line"> <span class="keyword">do!</span> Db.<span class="keyword">updateUser</span> { user <span class="keyword">with</span> Salt <span class="operator">=</span> salt; Hash <span class="operator">=</span> bcrypt salt req.NewPass }</span><br><span class="line"> <span class="keyword">do!</span> Log.info <span class="string">"Changed password for user %i"</span> user.Id</span><br><span class="line"> <span class="keyword">return</span> <span class="literal">Ok</span> ()</span><br><span class="line"> <span class="keyword">else</span> </span><br><span class="line"> <span class="keyword">do!</span> Log.error <span class="string">"Password change unauthorized: user %i"</span> user.Id</span><br><span class="line"> <span class="keyword">return</span> <span class="literal">Error</span> <span class="string">"Old password is invalid"</span></span><br><span class="line">}</span><br></pre></td></tr></table></figure> - <p>As you see, there’s no more <code>env</code> parameter being passed around. It’s now an implicit part of our effect expression. However at the moment we didn’t provide enough infrastructure in our code to make that thing work. What we’re going to need is a set of operators, we can use to make our computation expression happen.</p> -<p>First we’re going to need some <code>Effect<'env,'out></code> constructors:</p> +<p>First we’re going to need some <code>Effect<'env,'out></code> constructors:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">module</span> Effect <span class="operator">=</span></span><br><span class="line"> <span class="comment">/// Create value with no dependency requirements.</span></span><br><span class="line"> <span class="keyword">let</span> <span class="keyword">inline</span> value (x<span class="operator">:</span> <span class="symbol">'out</span>)<span class="operator">:</span> Effect<span class="operator"><</span><span class="symbol">'env</span>,<span class="symbol">'out</span><span class="operator">></span> <span class="operator">=</span> Effect (<span class="keyword">fun</span> _ <span class="operator">-></span> x)</span><br><span class="line"> <span class="comment">/// Create value which uses depenendency.</span></span><br><span class="line"> <span class="keyword">let</span> <span class="keyword">inline</span> apply (fn<span class="operator">:</span> <span class="symbol">'env</span> <span class="operator">-></span> <span class="symbol">'out</span>)<span class="operator">:</span> Effect<span class="operator"><</span><span class="symbol">'env</span>,<span class="symbol">'out</span><span class="operator">></span> <span class="operator">=</span> Effect fn</span><br></pre></td></tr></table></figure> - <p>We also need some way to run our effect to be able to make it… well effectful:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">module</span> Effect <span class="operator">=</span></span><br><span class="line"></span><br><span class="line"> <span class="comment">(* ...other functions... *)</span></span><br><span class="line"> </span><br><span class="line"> <span class="keyword">let</span> run (env<span class="operator">:</span> <span class="symbol">'env</span>) (Effect fn)<span class="operator">:</span> <span class="symbol">'out</span> <span class="operator">=</span> fn env</span><br></pre></td></tr></table></figure> - <p>And since we already mentioned <code>Effect</code> is monad, we also gonna need a <code>bind</code> function as well if we want to compose our effects together:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">module</span> Effect <span class="operator">=</span></span><br><span class="line"></span><br><span class="line"> <span class="comment">(* ...other functions... *)</span></span><br><span class="line"> </span><br><span class="line"> <span class="keyword">let</span> <span class="keyword">inline</span> bind (fn<span class="operator">:</span> <span class="symbol">'a</span> <span class="operator">-></span> Effect<span class="operator"><</span><span class="symbol">'env</span>,<span class="symbol">'b</span><span class="operator">></span>) effect <span class="operator">=</span></span><br><span class="line"> Effect (<span class="keyword">fun</span> env <span class="operator">-></span></span><br><span class="line"> <span class="keyword">let</span> x <span class="operator">=</span> run env effect <span class="comment">// compute result of the first effect</span></span><br><span class="line"> run env (fn x) <span class="comment">// run second effect, based on result of first one</span></span><br><span class="line"> )</span><br></pre></td></tr></table></figure> - <p>This is pretty much it. We’re just going to add compose all of these into builder type to make it usable as F# computation expression:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="meta">[<Struct>]</span></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">EffectBuilder</span> <span class="operator">=</span></span><br><span class="line"> <span class="keyword">member</span> <span class="keyword">inline</span> __.Return value <span class="operator">=</span> Effect.value value</span><br><span class="line"> <span class="keyword">member</span> <span class="keyword">inline</span> __.Zero () <span class="operator">=</span> Effect.value (Unchecked.defaultof<span class="operator"><</span>_<span class="operator">></span>)</span><br><span class="line"> <span class="keyword">member</span> <span class="keyword">inline</span> __.ReturnFrom (effect<span class="operator">:</span> Effect<span class="operator"><</span><span class="symbol">'env</span>, <span class="symbol">'out</span><span class="operator">></span>) <span class="operator">=</span> effect</span><br><span class="line"> <span class="keyword">member</span> <span class="keyword">inline</span> __.Bind(effect, fn) <span class="operator">=</span> Effect.bind fn effect</span><br><span class="line"> </span><br><span class="line"><span class="keyword">let</span> effect <span class="operator">=</span> EffectBuilder()</span><br></pre></td></tr></table></figure> - <p>Of course this, we still need to adapt the modules we prepared earlier to now operate on effects rater than plain functions. We can make this easier by using our <code>Effect.apply</code> function, like:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">module</span> Log <span class="operator">=</span> </span><br><span class="line"> <span class="keyword">let</span> debug fmt <span class="operator">=</span></span><br><span class="line"> <span class="keyword">let</span> ap s <span class="operator">=</span> Effect.apply (<span class="keyword">fun</span> (x<span class="operator">:</span> #ILog) <span class="operator">-></span> x.Logger.Debug s)</span><br><span class="line"> Printf.kprintf ap fmt</span><br></pre></td></tr></table></figure> - <p>So - as you may have noticed in final form of our effect-based <code>changePass</code> function - in result we almost fully erased all of the dependency-wiring code from our example. There are several downsides of this approach:</p> <ul> -<li>We do a lot of more bindings (see <code>let!</code>/<code>do!</code> expressions), which means more lambda closures, indirection (wait to see call stacks) and more allocations.</li> +<li>We do a lot of more bindings (see <code>let!</code>/<code>do!</code> expressions), which means more lambda closures, indirection (wait to see call stacks) and more allocations.</li> <li>Altogether we also erased <code>task { ... }</code> computation expression and with it an out-of-the-box ability to write asynchronous code. This is one of the downsides of using monads - cross-type composition is painful.</li> </ul> -<p>Of course we could enrich our <code>Effect</code> type to be able to bind it with <code>Task</code>/<code>Async</code>. That however means, that our pattern grows in complexity and becomes more of a framework rather than something to be easily applied into existing code. Is that bad? Not necessarily, but for sure comes with a bigger commitment, as now you’re not only writing business logic but eventually maintain new effect library. Maybe in future this concept will grow into its own space in favor of the F# ecosystem.</p> -<h2 id="Summary"><a href="#Summary" class="headerlink" title="Summary"></a>Summary</h2><p>We came from partial application as tool for dependency injection, over more structured approach promoting single environment type with help of powerful F# type inference, up to encapsulating it into a Reader Monad. That’s a long way. I hope you’ll give it a try and it will help you determine the approach that works for you.</p> +<p>Of course we could enrich our <code>Effect</code> type to be able to bind it with <code>Task</code>/<code>Async</code>. That however means, that our pattern grows in complexity and becomes more of a framework rather than something to be easily applied into existing code. Is that bad? Not necessarily, but for sure comes with a bigger commitment, as now you’re not only writing business logic but eventually maintain new effect library. Maybe in future this concept will grow into its own space in favor of the F# ecosystem.</p> +<h2 id="Summary"><a class="header-anchor" href="#Summary">¶</a>Summary</h2> +<p>We came from partial application as tool for dependency injection, over more structured approach promoting single environment type with help of powerful F# type inference, up to encapsulating it into a Reader Monad. That’s a long way. I hope you’ll give it a try and it will help you determine the approach that works for you.</p> ]]></content> <tags> <tag>Technique</tag> @@ -635,7 +605,6 @@ <url>/2025/03/30/F-%E9%87%8D%E8%BD%BD%E8%A7%A3%E6%9E%90%E9%97%AE%E9%A2%98/</url> <content><![CDATA[<p>当在 F# 中使用一些 C# 类库的时候,可能会遇到类似如下的问题:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">open</span> System</span><br><span class="line"><span class="keyword">open</span> System.Numerics</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> someFunction () <span class="operator">=</span></span><br><span class="line"> <span class="keyword">let</span> v<span class="operator">:</span> Vector<span class="operator"><</span><span class="type">byte</span><span class="operator">></span> <span class="operator">=</span> Vector(<span class="number">0</span>uy)</span><br><span class="line"> <span class="keyword">let</span> array<span class="operator">:</span> <span class="type">byte</span>[] <span class="operator">=</span> [<span class="operator">||</span>]</span><br><span class="line"> <span class="keyword">let</span> span<span class="operator">:</span> Span<span class="operator"><</span><span class="type">byte</span><span class="operator">></span> <span class="operator">=</span> Span(array)</span><br><span class="line"> v.CopyTo(span)</span><br><span class="line">Compiler error</span><br><span class="line"> v.CopyTo(span)</span><br><span class="line"> <span class="operator">----^^^^^^^^^^^^^^</span></span><br><span class="line"></span><br><span class="line"><span class="operator">/</span>home<span class="operator">/</span>muqiu<span class="operator">/</span>stdin(<span class="number">99</span>,<span class="number">5</span>)<span class="operator">:</span> error FS0041<span class="operator">:</span> A unique overload <span class="keyword">for</span> method <span class="symbol">'CopyTo</span>' could <span class="built_in">not</span> be determined based on <span class="keyword">type</span> information prior <span class="keyword">to</span> this program point. A <span class="keyword">type</span> annotation may be needed.</span><br><span class="line"></span><br><span class="line">Known <span class="keyword">type</span> <span class="title class_">of</span> argument<span class="operator">:</span> Span<span class="operator"><</span><span class="type">byte</span><span class="operator">></span></span><br><span class="line"></span><br><span class="line">Candidates<span class="operator">:</span></span><br><span class="line"> <span class="operator">-</span> Vector.CopyTo(destination<span class="operator">:</span> Span<span class="operator"><</span><span class="type">byte</span><span class="operator">></span>) <span class="operator">:</span> <span class="type">unit</span></span><br><span class="line"> <span class="operator">-</span> Vector.CopyTo(destination<span class="operator">:</span> Span<span class="operator"><</span><span class="type">byte</span><span class="operator">></span>) <span class="operator">:</span> <span class="type">unit</span></span><br></pre></td></tr></table></figure> - <p>编译器认为存在两个相同的 <code>CopyTo</code> 重载无法区分。但查阅文档发现,<code>Vector<T></code> 的 <code>CopyTo</code> 方法实际上只有一个匹配的重载(接受 <code>Span<T></code>),这似乎矛盾。</p> <p>这是因为 F# 编译器处理泛型方法重载的方式:</p> <ul> @@ -644,10 +613,10 @@ </ul> <p>仅我所知的一种解决方案是通过添加扩展方法显式指引编译器:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">type</span> <span class="title class_">Vector</span><span class="operator"><</span><span class="symbol">'T</span><span class="operator">></span> <span class="keyword">with</span></span><br><span class="line"> <span class="keyword">member</span> <span class="keyword">inline</span> this.CopyToByteSpan (span <span class="operator">:</span> Span<span class="operator"><</span><span class="type">byte</span><span class="operator">></span>) <span class="operator">=</span> </span><br><span class="line"> this.CopyTo(span) <span class="comment">// 显式绑定具体重载</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 调用时使用新方法</span></span><br><span class="line">v.CopyToByteSpan(span)</span><br></pre></td></tr></table></figure> - <p>这种方法通过创建具体的类型路径,帮助编译器绕过复杂的重载解析逻辑。</p> <p>学艺不精,不知道这是不是语言设计的差异,可能 F# 倾向于要求更明确的类型信息以避免意外行为?或许当泛型类型继承多个接口时,有没有可能出现在具体类型中不易察觉的隐式重载冲突?</p> -<h2 id="Refs"><a href="#Refs" class="headerlink" title="Refs."></a>Refs.</h2><ul> +<h2 id="Refs"><a class="header-anchor" href="#Refs">¶</a>Refs.</h2> +<ul> <li><a href="https://github.com/fsharp/fslang-suggestions/issues/905">“Most concrete” tiebreaker for generic overloads #905</a></li> <li><a href="https://github.com/dotnet/fsharp/issues/1647">Fail to resolve to non generic overload. #1647</a></li> </ul> @@ -659,13 +628,16 @@ <entry> <title>Fever of Unknown Origin</title> <url>/2023/11/16/Fever-of-Unknown-Origin/</url> - <content><![CDATA[<p>Fever of unknown origin (FUO) has been recognized as a disease state for over100 years.<br>The first commonly accepted definition of FUO was published in 1961 and included fever greater than 101F (38.3C) on multiple occasions at least 3 week duration of fever without identifiable cause despite at least a 1 week inpatient evaluation.</p> -<p>Overtime, this definition was considered both too rigid and too ill defined.<br>Given the impracticality of prolonged hospitalizations and advancing technology for diagnosis, the duration of work up was shortened to 3 days inpatient evaluation and/or 3 outpatient clinic visits.</p> + <content><![CDATA[<p>Fever of unknown origin (FUO) has been recognized as a disease state for over100 years.<br> +The first commonly accepted definition of FUO was published in 1961 and included fever greater than 101F (38.3C) on multiple occasions at least 3 week duration of fever without identifiable cause despite at least a 1 week inpatient evaluation.</p> +<p>Overtime, this definition was considered both too rigid and too ill defined.<br> +Given the impracticality of prolonged hospitalizations and advancing technology for diagnosis, the duration of work up was shortened to 3 days inpatient evaluation and/or 3 outpatient clinic visits.</p> <ul> <li><a href="/papers/Fever%20of%20Unknown%20Origin.pdf">Original Document</a></li> </ul> -<p>这是FUO(不明原因发烧)的综合指南,第一个普遍接受的 FUO 定义是1961 年发布的,包括多次发烧超过三十八度三,发烧持续时间至少 3 周,并且就算住院至少 1 周但仍无明确原因。后面这个定义被认为过于僵化且过于模糊。又改成了三天住院评估和/或三次门。除了有关评估持续时间的所有时间要求,还应该将 FUO 定义为完成最低限度检查后缺乏已知病因的发烧。</p> -<p>常见原因就感染性,自身免疫和结缔组织疾病,其他炎症过程和恶性肿瘤。结缔组织疾病和自身免疫性疾病是青少年 FUO 比儿童更常见的原因。<br>总体上有超过两百种病因可导致 FUO</p> +<p>这是FUO(不明原因发烧)的综合指南,第一个普遍接受的 FUO 定义是1961 年发布的,包括多次发烧超过三十八度三,发烧持续时间至少 3 周,并且就算住院至少 1 周但仍无明确原因。后面这个定义被认为过于僵化且过于模糊。又改成了三天住院评估和/或三次门。除了有关评估持续时间的所有时间要求,还应该将 FUO 定义为完成最低限度检查后缺乏已知病因的发烧。</p> +<p>常见原因就感染性,自身免疫和结缔组织疾病,其他炎症过程和恶性肿瘤。结缔组织疾病和自身免疫性疾病是青少年 FUO 比儿童更常见的原因。<br> +总体上有超过两百种病因可导致 FUO</p> ]]></content> <tags> <tag>Medicine</tag> @@ -685,7 +657,8 @@ <p>We saw in the previous post on message queues that one of the advantages of that approach was that the requests were “serialized” making it conceptually easier to deal with.</p> <p>There is a similar approach that can be used with events. The idea is to turn a series of events into an “event stream”. Event streams then become quite like IEnumerables, and so the obvious next step is to treat them in much the the same way that LINQ handles collections, so that they can be filtered, mapped, split and combined.</p> <p>F# has built in support for this model, as well as for the more traditional approach.</p> -<h2 id="A-simple-event-stream"><a href="#A-simple-event-stream" class="headerlink" title="A simple event stream"></a>A simple event stream</h2><p>Let’s start with a simple example to compare the two approaches. We’ll implement the classic event handler approach first.</p> +<h2 id="A-simple-event-stream"><a class="header-anchor" href="#A-simple-event-stream">¶</a>A simple event stream</h2> +<p>Let’s start with a simple example to compare the two approaches. We’ll implement the classic event handler approach first.</p> <p>First, we define a utility function that will:</p> <ul> <li>create a timer</li> @@ -694,60 +667,47 @@ </ul> <p>Here’s the code:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">open</span> System</span><br><span class="line"><span class="keyword">open</span> System.Threading</span><br><span class="line"></span><br><span class="line"><span class="comment">/// create a timer and register an event handler,</span></span><br><span class="line"><span class="comment">/// then run the timer for five seconds</span></span><br><span class="line"><span class="keyword">let</span> createTimer timerInterval eventHandler <span class="operator">=</span></span><br><span class="line"> <span class="comment">// setup a timer</span></span><br><span class="line"> <span class="keyword">let</span> timer <span class="operator">=</span> <span class="keyword">new</span> System.Timers.Timer(float timerInterval)</span><br><span class="line"> timer.AutoReset <span class="operator"><-</span> <span class="literal">true</span></span><br><span class="line"></span><br><span class="line"> <span class="comment">// add an event handler</span></span><br><span class="line"> timer.Elapsed.Add eventHandler</span><br><span class="line"></span><br><span class="line"> <span class="comment">// return an async task</span></span><br><span class="line"> <span class="keyword">async</span> {</span><br><span class="line"> <span class="comment">// start timer...</span></span><br><span class="line"> timer.Start()</span><br><span class="line"> <span class="comment">// ...run for five seconds...</span></span><br><span class="line"> <span class="keyword">do!</span> Async.Sleep <span class="number">5000</span></span><br><span class="line"> <span class="comment">// ... and stop</span></span><br><span class="line"> timer.Stop()</span><br><span class="line"> }</span><br></pre></td></tr></table></figure> - <p>Now test it interactively:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="comment">// create a handler. The event args are ignored</span></span><br><span class="line"><span class="keyword">let</span> basicHandler _ <span class="operator">=</span> <span class="built_in">printfn</span> <span class="string">"tick %A"</span> DateTime.Now</span><br><span class="line"></span><br><span class="line"><span class="comment">// register the handler</span></span><br><span class="line"><span class="keyword">let</span> basicTimer1 <span class="operator">=</span> createTimer <span class="number">1000</span> basicHandler</span><br><span class="line"></span><br><span class="line"><span class="comment">// run the task now</span></span><br><span class="line">Async.RunSynchronously basicTimer1</span><br></pre></td></tr></table></figure> - <p>Now let’s create a similar utility method to create a timer, but this time it will return an “observable” as well, which is the stream of events.</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> createTimerAndObservable timerInterval <span class="operator">=</span></span><br><span class="line"> <span class="comment">// setup a timer</span></span><br><span class="line"> <span class="keyword">let</span> timer <span class="operator">=</span> <span class="keyword">new</span> System.Timers.Timer(float timerInterval)</span><br><span class="line"> timer.AutoReset <span class="operator"><-</span> <span class="literal">true</span></span><br><span class="line"></span><br><span class="line"> <span class="comment">// events are automatically IObservable</span></span><br><span class="line"> <span class="keyword">let</span> observable <span class="operator">=</span> timer.Elapsed</span><br><span class="line"></span><br><span class="line"> <span class="comment">// return an async task</span></span><br><span class="line"> <span class="keyword">let</span> task <span class="operator">=</span> <span class="keyword">async</span> {</span><br><span class="line"> timer.Start()</span><br><span class="line"> <span class="keyword">do!</span> Async.Sleep <span class="number">5000</span></span><br><span class="line"> timer.Stop()</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="comment">// return a async task and the observable</span></span><br><span class="line"> (task,observable)</span><br></pre></td></tr></table></figure> - <p>And again test it interactively:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="comment">// create the timer and the corresponding observable</span></span><br><span class="line"><span class="keyword">let</span> basicTimer2 , timerEventStream <span class="operator">=</span> createTimerAndObservable <span class="number">1000</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// register that every time something happens on the</span></span><br><span class="line"><span class="comment">// event stream, print the time.</span></span><br><span class="line">timerEventStream</span><br><span class="line"><span class="operator">|></span> Observable.subscribe (<span class="keyword">fun</span> _ <span class="operator">-></span> <span class="built_in">printfn</span> <span class="string">"tick %A"</span> DateTime.Now)</span><br><span class="line"></span><br><span class="line"><span class="comment">// run the task now</span></span><br><span class="line">Async.RunSynchronously basicTimer2</span><br></pre></td></tr></table></figure> - <p>The difference is that instead of registering a handler directly with an event, we are “subscribing” to an event stream. Subtly different, and important.</p> -<h2 id="Counting-events"><a href="#Counting-events" class="headerlink" title="Counting events"></a>Counting events</h2><p>In this next example, we’ll have a slightly more complex requirement:</p> +<h2 id="Counting-events"><a class="header-anchor" href="#Counting-events">¶</a>Counting events</h2> +<p>In this next example, we’ll have a slightly more complex requirement:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">Create a timer that ticks every 500ms.</span><br><span class="line">At each tick, print the number of ticks so far and the current time.</span><br></pre></td></tr></table></figure> - <p>To do this in a classic imperative way, we would probably create a class with a mutable counter, as below:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">type</span> <span class="title class_">ImperativeTimerCount</span>() <span class="operator">=</span></span><br><span class="line"></span><br><span class="line"> <span class="keyword">let</span> <span class="keyword">mutable</span> count <span class="operator">=</span> <span class="number">0</span></span><br><span class="line"></span><br><span class="line"> <span class="comment">// the event handler. The event args are ignored</span></span><br><span class="line"> <span class="keyword">member</span> this.handleEvent _ <span class="operator">=</span></span><br><span class="line"> count <span class="operator"><-</span> count <span class="operator">+</span> <span class="number">1</span></span><br><span class="line"> <span class="built_in">printfn</span> <span class="string">"timer ticked with count %i"</span> count</span><br></pre></td></tr></table></figure> - <p>We can reuse the utility functions we created earlier to test it:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="comment">// create a handler class</span></span><br><span class="line"><span class="keyword">let</span> handler <span class="operator">=</span> <span class="keyword">new</span> ImperativeTimerCount()</span><br><span class="line"></span><br><span class="line"><span class="comment">// register the handler method</span></span><br><span class="line"><span class="keyword">let</span> timerCount1 <span class="operator">=</span> createTimer <span class="number">500</span> handler.handleEvent</span><br><span class="line"></span><br><span class="line"><span class="comment">// run the task now</span></span><br><span class="line">Async.RunSynchronously timerCount1</span><br></pre></td></tr></table></figure> - <p>Let’s see how we would do this same thing in a functional way:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="comment">// create the timer and the corresponding observable</span></span><br><span class="line"><span class="keyword">let</span> timerCount2, timerEventStream <span class="operator">=</span> createTimerAndObservable <span class="number">500</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// set up the transformations on the event stream</span></span><br><span class="line">timerEventStream</span><br><span class="line"><span class="operator">|></span> Observable.scan (<span class="keyword">fun</span> count _ <span class="operator">-></span> count <span class="operator">+</span> <span class="number">1</span>) <span class="number">0</span></span><br><span class="line"><span class="operator">|></span> Observable.subscribe (<span class="keyword">fun</span> count <span class="operator">-></span> <span class="built_in">printfn</span> <span class="string">"timer ticked with count %i"</span> count)</span><br><span class="line"></span><br><span class="line"><span class="comment">// run the task now</span></span><br><span class="line">Async.RunSynchronously timerCount2</span><br></pre></td></tr></table></figure> - <p>Here we see how you can build up layers of event transformations, just as you do with list transformations in LINQ.</p> <p>The first transformation is <code>scan</code>, which accumulates state for each event. It is roughly equivalent to the <code>List.fold</code> function that we have seen used with lists. In this case, the accumulated state is just a counter.</p> <p>And then, for each event, the count is printed out.</p> <p>Note that in this functional approach, we didn’t have any mutable state, and we didn’t need to create any special classes.</p> -<h2 id="Merging-multiple-event-streams"><a href="#Merging-multiple-event-streams" class="headerlink" title="Merging multiple event streams"></a>Merging multiple event streams</h2><p>For a final example, we’ll look at merging multiple event streams.</p> +<h2 id="Merging-multiple-event-streams"><a class="header-anchor" href="#Merging-multiple-event-streams">¶</a>Merging multiple event streams</h2> +<p>For a final example, we’ll look at merging multiple event streams.</p> <p>Let’s make a requirement based on the well-known “FizzBuzz” problem:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">Create two timers, called '3' and '5'. The '3' timer ticks every 300ms and the '5' timer ticks</span><br><span class="line">every 500ms.</span><br><span class="line"></span><br><span class="line">Handle the events as follows:</span><br><span class="line">a) for all events, print the id of the time and the time</span><br><span class="line">b) when a tick is simultaneous with a previous tick, print 'FizzBuzz'</span><br><span class="line">otherwise:</span><br><span class="line">c) when the '3' timer ticks on its own, print 'Fizz'</span><br><span class="line">d) when the '5' timer ticks on its own, print 'Buzz'</span><br></pre></td></tr></table></figure> - <p>First let’s create some code that both implementations can use.</p> <p>We’ll want a generic event type that captures the timer id and the time of the tick.</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">type</span> <span class="title class_">FizzBuzzEvent</span> <span class="operator">=</span> {label<span class="operator">:</span><span class="type">int</span>; time<span class="operator">:</span> DateTime}</span><br></pre></td></tr></table></figure> - <p>And then we need a utility function to see if two events are simultaneous. We’ll be generous and allow a time difference of up to 50ms.</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> areSimultaneous (earlierEvent,laterEvent) <span class="operator">=</span></span><br><span class="line"> <span class="keyword">let</span> {label<span class="operator">=</span>_;time<span class="operator">=</span>t1} <span class="operator">=</span> earlierEvent</span><br><span class="line"> <span class="keyword">let</span> {label<span class="operator">=</span>_;time<span class="operator">=</span>t2} <span class="operator">=</span> laterEvent</span><br><span class="line"> t2.Subtract(t1).Milliseconds <span class="operator"><</span> <span class="number">50</span></span><br></pre></td></tr></table></figure> - <p>In the imperative design, we’ll need to keep track of the previous event, so we can compare them. And we’ll need special case code for the first time, when the previous event doesn’t exist</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">type</span> <span class="title class_">ImperativeFizzBuzzHandler</span>() <span class="operator">=</span></span><br><span class="line"></span><br><span class="line"> <span class="keyword">let</span> <span class="keyword">mutable</span> previousEvent<span class="operator">:</span> FizzBuzzEvent <span class="type">option</span> <span class="operator">=</span> <span class="literal">None</span></span><br><span class="line"></span><br><span class="line"> <span class="keyword">let</span> printEvent thisEvent <span class="operator">=</span></span><br><span class="line"> <span class="keyword">let</span> {label<span class="operator">=</span><span class="built_in">id</span>; time<span class="operator">=</span>t} <span class="operator">=</span> thisEvent</span><br><span class="line"> <span class="built_in">printf</span> <span class="string">"[%i] %i.%03i "</span> <span class="built_in">id</span> t.Second t.Millisecond</span><br><span class="line"> <span class="keyword">let</span> simultaneous <span class="operator">=</span> previousEvent.IsSome <span class="operator">&&</span> areSimultaneous (previousEvent.Value,thisEvent)</span><br><span class="line"> <span class="keyword">if</span> simultaneous <span class="keyword">then</span> <span class="built_in">printfn</span> <span class="string">"FizzBuzz"</span></span><br><span class="line"> <span class="keyword">elif</span> <span class="built_in">id</span> <span class="operator">=</span> <span class="number">3</span> <span class="keyword">then</span> <span class="built_in">printfn</span> <span class="string">"Fizz"</span></span><br><span class="line"> <span class="keyword">elif</span> <span class="built_in">id</span> <span class="operator">=</span> <span class="number">5</span> <span class="keyword">then</span> <span class="built_in">printfn</span> <span class="string">"Buzz"</span></span><br><span class="line"></span><br><span class="line"> <span class="keyword">member</span> this.handleEvent3 eventArgs <span class="operator">=</span></span><br><span class="line"> <span class="keyword">let</span> event <span class="operator">=</span> {label<span class="operator">=</span><span class="number">3</span>; time<span class="operator">=</span>DateTime.Now}</span><br><span class="line"> printEvent event</span><br><span class="line"> previousEvent <span class="operator"><-</span> <span class="literal">Some</span> event</span><br><span class="line"></span><br><span class="line"> <span class="keyword">member</span> this.handleEvent5 eventArgs <span class="operator">=</span></span><br><span class="line"> <span class="keyword">let</span> event <span class="operator">=</span> {label<span class="operator">=</span><span class="number">5</span>; time<span class="operator">=</span>DateTime.Now}</span><br><span class="line"> printEvent event</span><br><span class="line"> previousEvent <span class="operator"><-</span> <span class="literal">Some</span> event</span><br></pre></td></tr></table></figure> - <p>Now the code is beginning to get ugly fast! Already we have mutable state, complex conditional logic, and special cases, just for such a simple requirement.</p> <p>Let’s test it:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="comment">// create the class</span></span><br><span class="line"><span class="keyword">let</span> handler <span class="operator">=</span> <span class="keyword">new</span> ImperativeFizzBuzzHandler()</span><br><span class="line"></span><br><span class="line"><span class="comment">// create the two timers and register the two handlers</span></span><br><span class="line"><span class="keyword">let</span> timer3 <span class="operator">=</span> createTimer <span class="number">300</span> handler.handleEvent3</span><br><span class="line"><span class="keyword">let</span> timer5 <span class="operator">=</span> createTimer <span class="number">500</span> handler.handleEvent5</span><br><span class="line"></span><br><span class="line"><span class="comment">// run the two timers at the same time</span></span><br><span class="line">[timer3;timer5]</span><br><span class="line"><span class="operator">|></span> Async.Parallel</span><br><span class="line"><span class="operator">|></span> Async.RunSynchronously</span><br></pre></td></tr></table></figure> - <p>It does work, but are you sure the code is not buggy? Are you likely to accidentally break something if you change it?</p> <p>The problem with this imperative code is that it has a lot of noise that obscures the the requirements.</p> <p>Can the functional version do better? Let’s see!</p> <p>First, we create <em>two</em> event streams, one for each timer:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> timer3, timerEventStream3 <span class="operator">=</span> createTimerAndObservable <span class="number">300</span></span><br><span class="line"><span class="keyword">let</span> timer5, timerEventStream5 <span class="operator">=</span> createTimerAndObservable <span class="number">500</span></span><br></pre></td></tr></table></figure> - <p>Next, we convert each event on the “raw” event streams into our FizzBuzz event type:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="comment">// convert the time events into FizzBuzz events with the appropriate id</span></span><br><span class="line"><span class="keyword">let</span> eventStream3 <span class="operator">=</span></span><br><span class="line"> timerEventStream3</span><br><span class="line"> <span class="operator">|></span> Observable.map (<span class="keyword">fun</span> _ <span class="operator">-></span> {label<span class="operator">=</span><span class="number">3</span>; time<span class="operator">=</span>DateTime.Now})</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> eventStream5 <span class="operator">=</span></span><br><span class="line"> timerEventStream5</span><br><span class="line"> <span class="operator">|></span> Observable.map (<span class="keyword">fun</span> _ <span class="operator">-></span> {label<span class="operator">=</span><span class="number">5</span>; time<span class="operator">=</span>DateTime.Now})</span><br></pre></td></tr></table></figure> - <p>Now, to see if two events are simultaneous, we need to compare them from the two different streams somehow.</p> <p>It’s actually easier than it sounds, because we can:</p> <ul> @@ -758,26 +718,21 @@ </ul> <p>Here’s the actual code to do this:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="comment">// combine the two streams</span></span><br><span class="line"><span class="keyword">let</span> combinedStream <span class="operator">=</span></span><br><span class="line"> Observable.merge eventStream3 eventStream5</span><br><span class="line"></span><br><span class="line"><span class="comment">// make pairs of events</span></span><br><span class="line"><span class="keyword">let</span> pairwiseStream <span class="operator">=</span></span><br><span class="line"> combinedStream <span class="operator">|></span> Observable.pairwise</span><br><span class="line"></span><br><span class="line"><span class="comment">// split the stream based on whether the pairs are simultaneous</span></span><br><span class="line"><span class="keyword">let</span> simultaneousStream, nonSimultaneousStream <span class="operator">=</span></span><br><span class="line"> pairwiseStream <span class="operator">|></span> Observable.partition areSimultaneous</span><br></pre></td></tr></table></figure> - <p>Finally, we can split the <code>nonSimultaneousStream</code> again, based on the event id:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="comment">// split the non-simultaneous stream based on the id</span></span><br><span class="line"><span class="keyword">let</span> fizzStream, buzzStream <span class="operator">=</span></span><br><span class="line"> nonSimultaneousStream</span><br><span class="line"> <span class="comment">// convert pair of events to the first event</span></span><br><span class="line"> <span class="operator">|></span> Observable.map (<span class="keyword">fun</span> (ev1,_) <span class="operator">-></span> ev1)</span><br><span class="line"> <span class="comment">// split on whether the event id is three</span></span><br><span class="line"> <span class="operator">|></span> Observable.partition (<span class="keyword">fun</span> {label<span class="operator">=</span><span class="built_in">id</span>} <span class="operator">-></span> <span class="built_in">id</span><span class="operator">=</span><span class="number">3</span>)</span><br></pre></td></tr></table></figure> - <p>Let’s review so far. We have started with the two original event streams and from them created four new ones:</p> <ul> <li><code>combinedStream</code> contains all the events</li> <li><code>simultaneousStream</code> contains only the simultaneous events</li> -<li><code>fizzStream</code> contains only the non-simultaneous events with id=3</li> -<li><code>buzzStream</code> contains only the non-simultaneous events with id=5</li> +<li><code>fizzStream</code> contains only the non-simultaneous events with id=3</li> +<li><code>buzzStream</code> contains only the non-simultaneous events with id=5</li> </ul> <p>Now all we need to do is attach behavior to each stream:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="comment">//print events from the combinedStream</span></span><br><span class="line">combinedStream</span><br><span class="line"><span class="operator">|></span> Observable.subscribe (<span class="keyword">fun</span> {label<span class="operator">=</span><span class="built_in">id</span>;time<span class="operator">=</span>t} <span class="operator">-></span></span><br><span class="line"> <span class="built_in">printf</span> <span class="string">"[%i] %i.%03i "</span> <span class="built_in">id</span> t.Second t.Millisecond)</span><br><span class="line"></span><br><span class="line"><span class="comment">//print events from the simultaneous stream</span></span><br><span class="line">simultaneousStream</span><br><span class="line"><span class="operator">|></span> Observable.subscribe (<span class="keyword">fun</span> _ <span class="operator">-></span> <span class="built_in">printfn</span> <span class="string">"FizzBuzz"</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">//print events from the nonSimultaneous streams</span></span><br><span class="line">fizzStream</span><br><span class="line"><span class="operator">|></span> Observable.subscribe (<span class="keyword">fun</span> _ <span class="operator">-></span> <span class="built_in">printfn</span> <span class="string">"Fizz"</span>)</span><br><span class="line"></span><br><span class="line">buzzStream</span><br><span class="line"><span class="operator">|></span> Observable.subscribe (<span class="keyword">fun</span> _ <span class="operator">-></span> <span class="built_in">printfn</span> <span class="string">"Buzz"</span>)</span><br></pre></td></tr></table></figure> - <p>Let’s test it:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="comment">// run the two timers at the same time</span></span><br><span class="line">[timer3;timer5]</span><br><span class="line"><span class="operator">|></span> Async.Parallel</span><br><span class="line"><span class="operator">|></span> Async.RunSynchronously</span><br></pre></td></tr></table></figure> - <p>Here’s all the code in one complete set:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="comment">// create the event streams and raw observables</span></span><br><span class="line"><span class="keyword">let</span> timer3, timerEventStream3 <span class="operator">=</span> createTimerAndObservable <span class="number">300</span></span><br><span class="line"><span class="keyword">let</span> timer5, timerEventStream5 <span class="operator">=</span> createTimerAndObservable <span class="number">500</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// convert the time events into FizzBuzz events with the appropriate id</span></span><br><span class="line"><span class="keyword">let</span> eventStream3 <span class="operator">=</span> timerEventStream3</span><br><span class="line"> <span class="operator">|></span> Observable.map (<span class="keyword">fun</span> _ <span class="operator">-></span> {label<span class="operator">=</span><span class="number">3</span>; time<span class="operator">=</span>DateTime.Now})</span><br><span class="line"><span class="keyword">let</span> eventStream5 <span class="operator">=</span> timerEventStream5</span><br><span class="line"> <span class="operator">|></span> Observable.map (<span class="keyword">fun</span> _ <span class="operator">-></span> {label<span class="operator">=</span><span class="number">5</span>; time<span class="operator">=</span>DateTime.Now})</span><br><span class="line"></span><br><span class="line"><span class="comment">// combine the two streams</span></span><br><span class="line"><span class="keyword">let</span> combinedStream <span class="operator">=</span></span><br><span class="line"> Observable.merge eventStream3 eventStream5</span><br><span class="line"></span><br><span class="line"><span class="comment">// make pairs of events</span></span><br><span class="line"><span class="keyword">let</span> pairwiseStream <span class="operator">=</span></span><br><span class="line"> combinedStream <span class="operator">|></span> Observable.pairwise</span><br><span class="line"></span><br><span class="line"><span class="comment">// split the stream based on whether the pairs are simultaneous</span></span><br><span class="line"><span class="keyword">let</span> simultaneousStream, nonSimultaneousStream <span class="operator">=</span></span><br><span class="line"> pairwiseStream <span class="operator">|></span> Observable.partition areSimultaneous</span><br><span class="line"></span><br><span class="line"><span class="comment">// split the non-simultaneous stream based on the id</span></span><br><span class="line"><span class="keyword">let</span> fizzStream, buzzStream <span class="operator">=</span></span><br><span class="line"> nonSimultaneousStream</span><br><span class="line"> <span class="comment">// convert pair of events to the first event</span></span><br><span class="line"> <span class="operator">|></span> Observable.map (<span class="keyword">fun</span> (ev1,_) <span class="operator">-></span> ev1)</span><br><span class="line"> <span class="comment">// split on whether the event id is three</span></span><br><span class="line"> <span class="operator">|></span> Observable.partition (<span class="keyword">fun</span> {label<span class="operator">=</span><span class="built_in">id</span>} <span class="operator">-></span> <span class="built_in">id</span><span class="operator">=</span><span class="number">3</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">//print events from the combinedStream</span></span><br><span class="line">combinedStream</span><br><span class="line"><span class="operator">|></span> Observable.subscribe (<span class="keyword">fun</span> {label<span class="operator">=</span><span class="built_in">id</span>;time<span class="operator">=</span>t} <span class="operator">-></span></span><br><span class="line"> <span class="built_in">printf</span> <span class="string">"[%i] %i.%03i "</span> <span class="built_in">id</span> t.Second t.Millisecond)</span><br><span class="line"></span><br><span class="line"><span class="comment">//print events from the simultaneous stream</span></span><br><span class="line">simultaneousStream</span><br><span class="line"><span class="operator">|></span> Observable.subscribe (<span class="keyword">fun</span> _ <span class="operator">-></span> <span class="built_in">printfn</span> <span class="string">"FizzBuzz"</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">//print events from the nonSimultaneous streams</span></span><br><span class="line">fizzStream</span><br><span class="line"><span class="operator">|></span> Observable.subscribe (<span class="keyword">fun</span> _ <span class="operator">-></span> <span class="built_in">printfn</span> <span class="string">"Fizz"</span>)</span><br><span class="line"></span><br><span class="line">buzzStream</span><br><span class="line"><span class="operator">|></span> Observable.subscribe (<span class="keyword">fun</span> _ <span class="operator">-></span> <span class="built_in">printfn</span> <span class="string">"Buzz"</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// run the two timers at the same time</span></span><br><span class="line">[timer3;timer5]</span><br><span class="line"><span class="operator">|></span> Async.Parallel</span><br><span class="line"><span class="operator">|></span> Async.RunSynchronously</span><br></pre></td></tr></table></figure> - <p>The code might seem a bit long winded, but this kind of incremental, step-wise approach is very clear and self-documenting.</p> <p>Some of the benefits of this style are:</p> <ul> @@ -787,9 +742,9 @@ <li>It is easy to debug. For example, I could easily “tap” the output of the <code>simultaneousStream</code> to see if it contains what I think it contains:</li> </ul> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="comment">// debugging code</span></span><br><span class="line"><span class="comment">//simultaneousStream |> Observable.subscribe (fun e -> printfn "sim %A" e)</span></span><br><span class="line"><span class="comment">//nonSimultaneousStream |> Observable.subscribe (fun e -> printfn "non-sim %A" e)</span></span><br></pre></td></tr></table></figure> - <p>This would be much harder in the imperative version.</p> -<h2 id="Summary"><a href="#Summary" class="headerlink" title="Summary"></a>Summary</h2><p>Functional Reactive Programming (known as FRP) is a big topic, and we’ve only just touched on it here. I hope this introduction has given you a glimpse of the usefulness of this way of doing things.</p> +<h2 id="Summary"><a class="header-anchor" href="#Summary">¶</a>Summary</h2> +<p>Functional Reactive Programming (known as FRP) is a big topic, and we’ve only just touched on it here. I hope this introduction has given you a glimpse of the usefulness of this way of doing things.</p> <p>If you want to learn more, see the documentation for the F# <a href="https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/ee370313%28v=vs.100%29?redirectedfrom=MSDN">Observable module</a>, which has the basic transformations used above. And there is also the <a href="https://docs.microsoft.com/en-us/previous-versions/dotnet/reactive-extensions/hh242985%28v=vs.103%29">Reactive Extensions (Rx)</a> library which shipped as part of .NET 4. That contains many other additional transformations.</p> ]]></content> <tags> @@ -803,12 +758,12 @@ <content><![CDATA[<ul> <li><a href="https://link.springer.com/chapter/10.1007/3-540-15975-4_50">The G-machine: A fast, graph-reduction evaluator</a></li> </ul> -<p>G-Machine 是一种通过图规约来对函数式语言程序求值的抽象架构。<br>与组合子规约不同,组合子规约的control是从表达式图本身动态导出的,而G-Machine是由通过编译Application表达式导出的指令序列指定的。</p> +<p>G-Machine 是一种通过图规约来对函数式语言程序求值的抽象架构。<br> +与组合子规约不同,组合子规约的control是从表达式图本身动态导出的,而G-Machine是由通过编译Application表达式导出的指令序列指定的。</p> <hr> <p>FP的程序基本上都可以用一个表达式的图表示,图计算机就是对这个图求值的机器,总的说来对图的求值是一个不停合并图上的节点生产新节点的过程。</p> <p>例如:</p> <figure class="highlight ocaml"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> x = <span class="number">2</span> + <span class="number">3</span> <span class="keyword">in</span> </span><br><span class="line"> x * x</span><br></pre></td></tr></table></figure> - <p>先计算出5,然后创建一个新的节点 <code>5 * 5</code>,然后再对这个节点求值,于是求值过程中就产生了很多临时的节点,这些中间节点也被叫做是 spine,求值过程是沿着 spine 进行的。</p> <p>但是这样就产生了很多额外的开销,lambda lifting 里提到:可以把程序里,很多捕捉了外围绑定的闭包函数中的这些绑定,转换成函数的参数,从而消除闭包,得到的这个函数就可以自由脱离作用域,被静态的编译到机器码里。这些被 float out 的函数也叫 supercombinator.</p> <p>在上面的代码中,如果不创建新的节点,顺序计算完了第一个 <code>x</code>,第二个 <code>x</code> 还会再被算一遍。</p> @@ -827,36 +782,41 @@ <title>多人协作系统中的实现策略 (CRDT,锁等实现方案)</title> <url>/2025/05/08/Multiplayer-Collaborative-Systems-tips/</url> <content><![CDATA[<p>最近碰到一块业务:在系统中可以存在多个用户同时对某个项目信息进行编辑,这种多人协作的场景挺有意思的,不过在我们的业务中,并不需要实时协作,只需要保证不会出错就行,话虽如此,但也可以探索一下实时协作的实现方案,防止老年痴呆。</p> -<p>先来看看第一个方案 —— CRDT(Conflict-free Replicated Data Type,无冲突可复制数据类型)是一类数据结构,它保证了在分布式节点(或多客户端)上进行离线/并发更新后,无需中心协调、也无需人工干预,通过“合并策略”就能得到一致的最终状态。 </p> +<p>先来看看第一个方案 —— CRDT(Conflict-free Replicated Data Type,无冲突可复制数据类型)是一类数据结构,它保证了在分布式节点(或多客户端)上进行离线/并发更新后,无需中心协调、也无需人工干预,通过“合并策略”就能得到一致的最终状态。</p> <p>核心思想是:所有并发操作都是幂等(idempotent)、可交换(commutative)的。</p> -<p>常见类型有:<br>一、G-Counter(只能增计数器)<br>二、PN-Counter(可增可减计数器)<br>三、LWW-Register(最后写入胜出)<br>四、结合 JSON 的树型 CRDT(如 <a href="https://github.com/automerge/automerge">Automerge</a> / <a href="https://yjs.dev/">Yjs</a>) </p> -<p>更多原理可参考 Decipad 博客“Collaborative and Offline Editing Using CRDTs”[^1]。</p> +<p>常见类型有:<br> +一、G-Counter(只能增计数器)<br> +二、PN-Counter(可增可减计数器)<br> +三、LWW-Register(最后写入胜出)<br> +四、结合 JSON 的树型 CRDT(如 <a href="https://github.com/automerge/automerge">Automerge</a> / <a href="https://yjs.dev/">Yjs</a>)</p> +<p>更多原理可参考 Decipad 博客“Collaborative and Offline Editing Using CRDTs”<sup class="footnote-ref"><a href="#fn1" id="fnref1">[1]</a></sup>。</p> <blockquote> <p>有一个挺有趣的 Rust 项目 <a href="https://github.com/loro-dev/loro">Loro: Make your JSON data collaborative and version-controlled with CRDTs</a></p> </blockquote> -<p>假设我的项目信息编辑页面允许多人实时/离线修改某个研究项目的“名称”、“描述”字段,前端用 SvelteKit + GraphQL 获取和提交变更:</p> +<p>假设我的项目信息编辑页面允许多人实时/离线修改某个研究项目的“名称”、“描述”字段,前端用 SvelteKit + GraphQL 获取和提交变更:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">┌── 用户 A 离线修改了 “description” 的若干段文本 </span><br><span class="line">└── 用户 B 同时在线修改了同一字段的其他段落 </span><br></pre></td></tr></table></figure> - <p>如果后端使用 CRDT(比如把 <code>description</code> 用 JSON-CRDT 存储),两次修改只要在任意顺序合并都能得到完整的内容:</p> -<p>首先,A 客户端本地 apply 操作并缓存,恢复网络后推给服务器;<br>然后,服务器用 CRDT merge(A.delta, B.delta),得到一致文档<br>最后,服务器广播新文档到所有客户端,A/B 均得到相同结果 </p> +<p>首先,A 客户端本地 apply 操作并缓存,恢复网络后推给服务器;<br> +然后,服务器用 CRDT merge(A.delta, B.delta),得到一致文档<br> +最后,服务器广播新文档到所有客户端,A/B 均得到相同结果</p> <hr> -<p>好了说点实际符合业务场景的方案,首先想到的是悲观锁(Pessimistic Locking) ,思路是:用户打开编辑界面时,向后端申请“锁” → 其它用户尝试编辑时被拒绝 → 编辑完成后释放锁/超时自动释放。 </p> +<p>好了说点实际符合业务场景的方案,首先想到的是悲观锁(Pessimistic Locking) ,思路是:用户打开编辑界面时,向后端申请“锁” → 其它用户尝试编辑时被拒绝 → 编辑完成后释放锁/超时自动释放。</p> <p>假如有一个这样的锁表:</p> -<pre><code class="sql">CREATE TABLE project_lock ( +<pre><code class="language-sql">CREATE TABLE project_lock ( project_id UUID PRIMARY KEY, locked_by UUID NOT NULL, expires_at TIMESTAMPTZ NOT NULL ); </code></pre> <p>可以在事务内申请它:</p> -<pre><code class="ts">const now = new Date(); +<pre><code class="language-ts">const now = new Date(); const expires = new Date(now.getTime() + 5*60*1000); // 5 分钟后过期 await prisma.$transaction(async tx => { const existing = await tx.project_lock.findUnique({ where:{ project_id } }); if (existing && existing.expires_at > now) { - throw new Error('项目正被人编辑'); - } + throw new Error('项目正被人编辑'); + } await tx.project_lock.upsert({ where: { project_id }, @@ -866,14 +826,16 @@ await prisma.$transaction(async tx => { }); </code></pre> <p>释放锁就直接从锁表里删掉对应的数据即可:</p> -<pre><code class="ts">await prisma.project_lock.delete({ where:{ project_id } }); +<pre><code class="language-ts">await prisma.project_lock.delete({ where:{ project_id } }); </code></pre> <p>前端的话,大概就是:</p> -<p>在进入编辑前请求一下 <code>/api/project/:id/lock</code> 之类的 API,失败则提示“被占用”;<br>在 <code>onbeforeunload</code> 时执行 <code>/unlock</code>;<br>超时后后端自动允许新锁。 </p> +<p>在进入编辑前请求一下 <code>/api/project/:id/lock</code> 之类的 API,失败则提示“被占用”;<br> +在 <code>onbeforeunload</code> 时执行 <code>/unlock</code>;<br> +超时后后端自动允许新锁。</p> <hr> -<p>第二个方案是乐观并发控制(Optimistic Concurrency) :记录资源的版本号或时间戳;客户端提交更新时带上自己的版本号,后端检查版本是否一致,不一致则认为冲突,返回 409,由客户端告知用户“数据已过期,请刷新后合并”。 </p> +<p>第二个方案是乐观并发控制(Optimistic Concurrency) :记录资源的版本号或时间戳;客户端提交更新时带上自己的版本号,后端检查版本是否一致,不一致则认为冲突,返回 409,由客户端告知用户“数据已过期,请刷新后合并”。</p> <p>具体实现中,可以尝试在 <code>project</code> 表加上 <code>version INT NOT NULL DEFAULT 1, updated_at TIMESTAMPTZ</code> ,然后更新项目时:</p> -<pre><code class="ts">async updateProject(parent, { id, version, input }, ctx) { +<pre><code class="language-ts">async updateProject(parent, { id, version, input }, ctx) { const result = await prisma.$executeRaw` UPDATE project SET name = ${input.name}, @@ -881,38 +843,51 @@ await prisma.$transaction(async tx => { version = version + 1, updated_at = now() WHERE id = ${id} AND version = ${version} - `; + `; if (result === 0) { - throw new ConflictException('版本冲突,请刷新后重试'); + throw new ConflictException('版本冲突,请刷新后重试'); } return prisma.project.findUnique({ where:{ id } }); } </code></pre> -<p>前端捕获到冲突错误可以用一个弹窗提示“另有用户已更新此项目,是否合并/重新加载?” 之类的玩意儿。</p> +<p>前端捕获到冲突错误可以用一个弹窗提示“另有用户已更新此项目,是否合并/重新加载?” 之类的玩意儿。</p> <hr> -<p>第三个方案是:操作转化(Operational Transformation,OT) </p> -<p>也就是记录用户每次的“操作”(insert/delete at position),服务器根据历史操作序列对并发操作做转化(transform),确保先到达的操作调整后再应用后到达的。 </p> -<p>有一些实现案例:<br>一、ShareDB(Node.js)<br>二、Google Docs 中的同步算法 </p> -<p>具体实现的话,可能要现在前端逐字符/块地包装成操作并 WebSocket 推送,服务器再维护一个“操作历史队列”,每来一个 op 就 transform 并 broadcast,而客户端收到广播后,按顺序 replay 保证视图一致。</p> +<p>第三个方案是:操作转化(Operational Transformation,OT)</p> +<p>也就是记录用户每次的“操作”(insert/delete at position),服务器根据历史操作序列对并发操作做转化(transform),确保先到达的操作调整后再应用后到达的。</p> +<p>有一些实现案例:<br> +一、ShareDB(Node.js)<br> +二、Google Docs 中的同步算法</p> +<p>具体实现的话,可能要现在前端逐字符/块地包装成操作并 WebSocket 推送,服务器再维护一个“操作历史队列”,每来一个 op 就 transform 并 broadcast,而客户端收到广播后,按顺序 replay 保证视图一致。</p> <hr> <p>最后可能还可以用事件溯源(Event Sourcing)+ 场景命令模式来实现:</p> -<p>不直接存状态,而是存所有“命令 / 事件”(Event),回放事件得到当前状态。冲突通过合并策略或补偿事件(Compensating Events)解决。 </p> -<p>例如:<br>在每次更新时推送 <code>ProjectUpdated { projectId, fieldsChanged, userId, timestamp }</code> ,<br>然后写入事件存储(如 Kafka / EventStoreDB),<br>读端 Consumer 按顺序重建最新状态或按领域聚合 ,<br>最后在并发时如果两个事件都修改了同一字段,可在写端做校验/补偿,或在读端做最后写入胜出等策略 。</p> +<p>不直接存状态,而是存所有“命令 / 事件”(Event),回放事件得到当前状态。冲突通过合并策略或补偿事件(Compensating Events)解决。</p> +<p>例如:<br> +在每次更新时推送 <code>ProjectUpdated { projectId, fieldsChanged, userId, timestamp }</code> ,<br> +然后写入事件存储(如 Kafka / EventStoreDB),<br> +读端 Consumer 按顺序重建最新状态或按领域聚合 ,<br> +最后在并发时如果两个事件都修改了同一字段,可在写端做校验/补偿,或在读端做最后写入胜出等策略 。</p> <hr> <p>总结来说,</p> <ul> -<li>CRDT 最擅长 去中心化、离线编辑、自动合并; </li> -<li>若不引入 CRDT,可根据业务侧重点选用: <ol> -<li>悲观锁 → 强制串行编辑,简单粗暴; </li> -<li>乐观并发 → 适合大多数业务场景,成本低; </li> -<li>OT → 适合富文本或实时协同场景,复杂度中等; </li> +<li>CRDT 最擅长 去中心化、离线编辑、自动合并;</li> +<li>若不引入 CRDT,可根据业务侧重点选用: +<ol> +<li>悲观锁 → 强制串行编辑,简单粗暴;</li> +<li>乐观并发 → 适合大多数业务场景,成本低;</li> +<li>OT → 适合富文本或实时协同场景,复杂度中等;</li> <li>事件溯源 → 适合需要全历史审计、可回放的场景。</li> </ol> </li> </ul> <hr> -<p>[^1]: Decipad 博客 “Collaborative and Offline Editing Using CRDTs”<br> <a href="https://www.decipad.com/blog/decipads-innovative-method-collaborative-and-offline-editing-using-crdts">https://www.decipad.com/blog/decipads-innovative-method-collaborative-and-offline-editing-using-crdts</a></p> -<p>[^2]: Hacker News 讨论(CRDT 相关线程)<br> <a href="https://news.ycombinator.com/item?id=38289327">https://news.ycombinator.com/item?id=38289327</a></p> +<hr class="footnotes-sep"> +<section class="footnotes"> +<ol class="footnotes-list"> +<li id="fn1" class="footnote-item"><p>Decipad 博客 “Collaborative and Offline Editing Using CRDTs”<br> +<a href="https://www.decipad.com/blog/decipads-innovative-method-collaborative-and-offline-editing-using-crdts">https://www.decipad.com/blog/decipads-innovative-method-collaborative-and-offline-editing-using-crdts</a> <a href="#fnref1" class="footnote-backref">↩︎</a></p> +</li> +</ol> +</section> ]]></content> <tags> <tag>Technique</tag> @@ -927,10 +902,12 @@ await prisma.$transaction(async tx => { <p>现在,需要获取前 10 个用户以及他们各自的所有帖子。</p> <p>一种有问题的 ORM 实现(或不当的使用方式)可能会这样执行:</p> <ol> -<li>第一次查询 (The “1”): 获取前 10 个用户。<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span> <span class="keyword">FROM</span> <span class="keyword">User</span> LIMIT <span class="number">10</span>;</span><br></pre></td></tr></table></figure></li> -<li>接下来的 N (=10) 次查询 (The “N”): 对于上一步获取到的每一个用户,单独执行一次查询来获取该用户的帖子。<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="comment">-- 用户 1</span></span><br><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span> <span class="keyword">FROM</span> Post <span class="keyword">WHERE</span> authorId <span class="operator">=</span> <span class="number">1</span>;</span><br><span class="line"><span class="comment">-- 用户 2</span></span><br><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span> <span class="keyword">FROM</span> Post <span class="keyword">WHERE</span> authorId <span class="operator">=</span> <span class="number">2</span>;</span><br><span class="line"><span class="comment">-- 用户 3</span></span><br><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span> <span class="keyword">FROM</span> Post <span class="keyword">WHERE</span> authorId <span class="operator">=</span> <span class="number">3</span>;</span><br><span class="line"><span class="comment">-- ... 直到 用户 10</span></span><br><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span> <span class="keyword">FROM</span> Post <span class="keyword">WHERE</span> authorId <span class="operator">=</span> <span class="number">10</span>;</span><br></pre></td></tr></table></figure></li> +<li>第一次查询 (The “1”): 获取前 10 个用户。<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span> <span class="keyword">FROM</span> <span class="keyword">User</span> LIMIT <span class="number">10</span>;</span><br></pre></td></tr></table></figure> +</li> +<li>接下来的 N (=10) 次查询 (The “N”): 对于上一步获取到的每一个用户,单独执行一次查询来获取该用户的帖子。<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="comment">-- 用户 1</span></span><br><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span> <span class="keyword">FROM</span> Post <span class="keyword">WHERE</span> authorId <span class="operator">=</span> <span class="number">1</span>;</span><br><span class="line"><span class="comment">-- 用户 2</span></span><br><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span> <span class="keyword">FROM</span> Post <span class="keyword">WHERE</span> authorId <span class="operator">=</span> <span class="number">2</span>;</span><br><span class="line"><span class="comment">-- 用户 3</span></span><br><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span> <span class="keyword">FROM</span> Post <span class="keyword">WHERE</span> authorId <span class="operator">=</span> <span class="number">3</span>;</span><br><span class="line"><span class="comment">-- ... 直到 用户 10</span></span><br><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span> <span class="keyword">FROM</span> Post <span class="keyword">WHERE</span> authorId <span class="operator">=</span> <span class="number">10</span>;</span><br></pre></td></tr></table></figure> +</li> </ol> -<p>在这个场景下,总共执行了 1 + 10 = 11 次数据库查询。如果 N 的值很大(比如获取 1000 个用户),就会产生 1001 次查询,这对数据库造成巨大的、不必要的压力,并显著增加应用程序的响应时间。每一次数据库交互都有网络延迟和数据库处理的开销,N+1 次查询会将这些开销放大 N 倍。</p> +<p>在这个场景下,总共执行了 1 + 10 = 11 次数据库查询。如果 N 的值很大(比如获取 1000 个用户),就会产生 1001 次查询,这对数据库造成巨大的、不必要的压力,并显著增加应用程序的响应时间。每一次数据库交互都有网络延迟和数据库处理的开销,N+1 次查询会将这些开销放大 N 倍。</p> <p>N+1 问题通常源于 ORM 处理关联数据的方式,特别是与“懒加载”(Lazy Loading)相关的策略。懒加载是指只有在显式访问关联属性时,ORM 才会去数据库加载这些数据。虽然这在某些情况下可以避免加载不需要的数据,但如果在循环中访问关联属性,就很容易触发 N+1 问题。</p> <p>然而,问题的根源在于没有有效地预先加载(或批量加载)所需的关联数据。即使不使用严格意义上的懒加载,如果 ORM 在处理关联查询时不够智能,采用了逐个获取关联对象的策略,同样会产生 N+1 查询。</p> <p>在 Prisma 出现之前或在其他 ORM 中,解决 N+1 问题常见的方法包括:</p> @@ -941,14 +918,16 @@ await prisma.$transaction(async tx => { <p>Prisma ORM 在设计上就考虑了 N+1 问题,并提供了一种既方便开发者又高效的解决方案。当使用 Prisma Client 查询数据并需要包含关联模型时,Prisma 会自动优化查询,避免产生 N+1 查询,主要通过关系查询(Relation Queries)中的 <code>include</code> 选项或嵌套读取(nested reads)来实现这一点:</p> <p>假设想获取所有用户及其发布的帖子,使用 Prisma Client,可以这样写:</p> <figure class="highlight typescript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> { <span class="title class_">PrismaClient</span> } <span class="keyword">from</span> <span class="string">'@prisma/client'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> prisma = <span class="keyword">new</span> <span class="title class_">PrismaClient</span>()</span><br><span class="line"></span><br><span class="line"><span class="keyword">async</span> <span class="keyword">function</span> <span class="title function_">getUsersWithPosts</span>(<span class="params"></span>) {</span><br><span class="line"> <span class="keyword">const</span> usersWithPosts = <span class="keyword">await</span> prisma.<span class="property">user</span>.<span class="title function_">findMany</span>({</span><br><span class="line"> <span class="attr">include</span>: {</span><br><span class="line"> <span class="attr">posts</span>: <span class="literal">true</span>, <span class="comment">// 指示 Prisma 加载关联的 posts</span></span><br><span class="line"> },</span><br><span class="line"> })</span><br><span class="line"> <span class="comment">// usersWithPosts 包含了用户列表,每个用户对象中都有一个 posts 数组</span></span><br><span class="line"> <span class="variable language_">console</span>.<span class="title function_">log</span>(usersWithPosts)</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="title function_">getUsersWithPosts</span>()</span><br><span class="line"> .<span class="title function_">catch</span>(<span class="function">(<span class="params">e</span>) =></span> {</span><br><span class="line"> <span class="keyword">throw</span> e</span><br><span class="line"> })</span><br><span class="line"> .<span class="title function_">finally</span>(<span class="title function_">async</span> () => {</span><br><span class="line"> <span class="keyword">await</span> prisma.$disconnect()</span><br><span class="line"> })</span><br></pre></td></tr></table></figure> - <p>当执行上述查询时,Prisma 不会 生成 N+1 个 SQL 查询。而是首先会分析请求,并将其转化为数量非常有限的高效 SQL 查询。对于上面这个一对多关系的 <code>include</code> 查询,Prisma 通常会执行以下两步(类似于批量加载策略):</p> <ol> -<li>查询父模型: 获取所有 <code>User</code> 记录。<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> "public"."User"."id", "public"."User"."name", <span class="comment">/* ... other user fields */</span> <span class="keyword">FROM</span> "public"."User" <span class="keyword">WHERE</span> <span class="number">1</span><span class="operator">=</span><span class="number">1</span></span><br></pre></td></tr></table></figure></li> -<li>查询关联的子模型: 使用上一步获取到的所有用户 <code>id</code>,通过 <code>WHERE IN (...)</code> 子句一次性查询所有相关的 <code>Post</code> 记录。<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> "public"."Post"."id", "public"."Post"."title", "public"."Post"."authorId", <span class="comment">/* ... other post fields */</span> <span class="keyword">FROM</span> "public"."Post" <span class="keyword">WHERE</span> "public"."Post"."authorId" <span class="keyword">IN</span> ($<span class="number">1</span>, $<span class="number">2</span>, $<span class="number">3</span>, ...) <span class="comment">/* 这里的 $1, $2, ... 是第一步查到的用户 ID 列表 */</span></span><br></pre></td></tr></table></figure></li> +<li>查询父模型: 获取所有 <code>User</code> 记录。<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> "public"."User"."id", "public"."User"."name", <span class="comment">/* ... other user fields */</span> <span class="keyword">FROM</span> "public"."User" <span class="keyword">WHERE</span> <span class="number">1</span><span class="operator">=</span><span class="number">1</span></span><br></pre></td></tr></table></figure> +</li> +<li>查询关联的子模型: 使用上一步获取到的所有用户 <code>id</code>,通过 <code>WHERE IN (...)</code> 子句一次性查询所有相关的 <code>Post</code> 记录。<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> "public"."Post"."id", "public"."Post"."title", "public"."Post"."authorId", <span class="comment">/* ... other post fields */</span> <span class="keyword">FROM</span> "public"."Post" <span class="keyword">WHERE</span> "public"."Post"."authorId" <span class="keyword">IN</span> ($<span class="number">1</span>, $<span class="number">2</span>, $<span class="number">3</span>, ...) <span class="comment">/* 这里的 $1, $2, ... 是第一步查到的用户 ID 列表 */</span></span><br></pre></td></tr></table></figure> +</li> </ol> <p>Prisma Client 在内存中将这两次查询的结果高效地组合起来,最终返回嵌套的、符合 TypeScript 类型的数据。</p> -<h2 id="Refs"><a href="#Refs" class="headerlink" title="Refs."></a>Refs.</h2><ul> +<h2 id="Refs"><a class="header-anchor" href="#Refs">¶</a>Refs.</h2> +<ul> <li><a href="https://stackoverflow.com/questions/97197/what-is-the-n1-selects-problem-in-orm-object-relational-mapping">Stack Overflow: What is the N+1 selects problem in ORM?</a></li> <li><a href="https://www.prisma.io/docs/orm/prisma-client/queries/query-optimization-performance#solving-the-n1-problem">Prisma Docs: Solving the N+1 problem</a></li> </ul> @@ -960,9 +939,12 @@ await prisma.$transaction(async tx => { <entry> <title>.NET AOT 下的 F# 命令行参数解析库选择</title> <url>/2024/06/06/NET-AOT-%E4%B8%8B%E7%9A%84-F-%E5%91%BD%E4%BB%A4%E8%A1%8C%E5%8F%82%E6%95%B0%E8%A7%A3%E6%9E%90%E5%BA%93%E9%80%89%E6%8B%A9/</url> - <content><![CDATA[<p>Argu 不支持 AOT,不过用 F# 的话可以看整个 .NET 的生态,我看了一下 C# 的 CommandLineParser:<br><a href="https://github.com/commandlineparser">https://github.com/commandlineparser</a></p> -<p>在这个 PR 中支持了 Native AOT<br><a href="https://github.com/commandlineparser/commandline/pull/913">https://github.com/commandlineparser/commandline/pull/913</a></p> -<p>除此之外,还有一个更加精巧的 F# 库可以用,只有两百多行:<br><a href="https://github.com/B2R2-org/FsOptParse/">https://github.com/B2R2-org/FsOptParse/</a></p> + <content><![CDATA[<p>Argu 不支持 AOT,不过用 F# 的话可以看整个 .NET 的生态,我看了一下 C# 的 CommandLineParser:<br> +<a href="https://github.com/commandlineparser">https://github.com/commandlineparser</a></p> +<p>在这个 PR 中支持了 Native AOT<br> +<a href="https://github.com/commandlineparser/commandline/pull/913">https://github.com/commandlineparser/commandline/pull/913</a></p> +<p>除此之外,还有一个更加精巧的 F# 库可以用,只有两百多行:<br> +<a href="https://github.com/B2R2-org/FsOptParse/">https://github.com/B2R2-org/FsOptParse/</a></p> <p>AOT 后的大小很可观,并且支持 full trim.</p> <p>用例:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="comment">(** defines a state to pass to the option parser *)</span></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">opts</span> <span class="operator">=</span></span><br><span class="line"> {</span><br><span class="line"> optX <span class="operator">:</span> <span class="type">int</span>;</span><br><span class="line"> optY <span class="operator">:</span> <span class="type">bool</span>;</span><br><span class="line"> optZ <span class="operator">:</span> <span class="type">string</span>;</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"><span class="comment">(** default option state *)</span></span><br><span class="line"><span class="keyword">let</span> defaultOpts <span class="operator">=</span></span><br><span class="line"> {</span><br><span class="line"> optX <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line"> optY <span class="operator">=</span> <span class="literal">false</span>;</span><br><span class="line"> optZ <span class="operator">=</span> <span class="string">""</span>;</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"><span class="comment">(*</span></span><br><span class="line"><span class="comment"> An example command line specification, which is a list of Options.</span></span><br><span class="line"><span class="comment"> Each Option describes a command line option (switch) that is specified with</span></span><br><span class="line"><span class="comment"> either a short (a single-dash option) or long option (a double-dash option).</span></span><br><span class="line"><span class="comment">*)</span></span><br><span class="line"><span class="keyword">let</span> spec <span class="operator">=</span></span><br><span class="line"> [</span><br><span class="line"> <span class="comment">(* This option can be specified with -x <NUM>. There is an extra argument to</span></span><br><span class="line"><span class="comment"> specify a value in integer. *)</span></span><br><span class="line"> Option (<span class="comment">(* description of the option *)</span></span><br><span class="line"> descr<span class="operator">=</span><span class="string">"this is a testing param X"</span>,</span><br><span class="line"> <span class="comment">(* how many extra argument must be provided by a user? *)</span></span><br><span class="line"> extra<span class="operator">=</span><span class="number">1</span>,</span><br><span class="line"> <span class="comment">(* callback sets up the option and returns it *)</span></span><br><span class="line"> callback<span class="operator">=</span>(<span class="keyword">fun</span> opts arg <span class="operator">-></span> {opts <span class="keyword">with</span> optX<span class="operator">=</span>(int) arg.[<span class="number">0</span>]}),</span><br><span class="line"> <span class="comment">(* use a short option style -x *)</span></span><br><span class="line"> short<span class="operator">=</span><span class="string">"-x"</span></span><br><span class="line"> );</span><br><span class="line"></span><br><span class="line"> <span class="comment">(* This option can be specified with -y. There is no extra argument. This</span></span><br><span class="line"><span class="comment"> option just sets a flag, optY. *)</span></span><br><span class="line"> Option (<span class="comment">(* description of the option *)</span></span><br><span class="line"> descr<span class="operator">=</span><span class="string">"this is a testing param Y"</span>,</span><br><span class="line"> <span class="comment">(* set the option to be true *)</span></span><br><span class="line"> callback<span class="operator">=</span>(<span class="keyword">fun</span> opts _ <span class="operator">-></span> {opts <span class="keyword">with</span> optY<span class="operator">=</span><span class="literal">true</span>}),</span><br><span class="line"> <span class="comment">(* use a short option style (-y) *)</span></span><br><span class="line"> short<span class="operator">=</span><span class="string">"-y"</span>,</span><br><span class="line"> <span class="comment">(* also use a long option style (--yoohoo) *)</span></span><br><span class="line"> long<span class="operator">=</span><span class="string">"--yoohoo"</span></span><br><span class="line"> );</span><br><span class="line"></span><br><span class="line"> <span class="comment">(* A dummy option to pretty-print the usage *)</span></span><br><span class="line"> Option (<span class="comment">(* description of the option *)</span></span><br><span class="line"> descr<span class="operator">=</span><span class="string">""</span>,</span><br><span class="line"> dummy<span class="operator">=</span><span class="literal">true</span></span><br><span class="line"> );</span><br><span class="line"> Option (<span class="comment">(* description of the option *)</span></span><br><span class="line"> descr<span class="operator">=</span><span class="string">"[Required Options]"</span>,</span><br><span class="line"> descrColor<span class="operator">=</span>System.ConsoleColor.DarkCyan,</span><br><span class="line"> dummy<span class="operator">=</span><span class="literal">true</span></span><br><span class="line"> );</span><br><span class="line"></span><br><span class="line"> <span class="comment">(* The third option is a required option. In other words, option parsing</span></span><br><span class="line"><span class="comment"> will raise an exception if this option is not given by a user. This</span></span><br><span class="line"><span class="comment"> option takes in an additional integer argument, and set it to the global</span></span><br><span class="line"><span class="comment"> variable z. *)</span></span><br><span class="line"> Option (<span class="comment">(* description of the option *)</span></span><br><span class="line"> descr<span class="operator">=</span><span class="string">"required parameter <STRING> with an integer option"</span>,</span><br><span class="line"> <span class="comment">(* callback to set the optZ value *)</span></span><br><span class="line"> callback<span class="operator">=</span>(<span class="keyword">fun</span> opts arg <span class="operator">-></span> {opts <span class="keyword">with</span> optZ<span class="operator">=</span>arg.[<span class="number">0</span>]}),</span><br><span class="line"> <span class="comment">(* specifying this is a required option *)</span></span><br><span class="line"> required<span class="operator">=</span><span class="literal">true</span>,</span><br><span class="line"> <span class="comment">(* one additional argument to specify an integer value *)</span></span><br><span class="line"> extra<span class="operator">=</span><span class="number">1</span>,</span><br><span class="line"> <span class="comment">(* use only a long option style *)</span></span><br><span class="line"> long<span class="operator">=</span><span class="string">"--req"</span></span><br><span class="line"> );</span><br><span class="line"> ]</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> _ <span class="operator">=</span></span><br><span class="line"> <span class="keyword">let</span> prog <span class="operator">=</span> <span class="string">"opttest.fsx"</span></span><br><span class="line"> <span class="keyword">let</span> args <span class="operator">=</span> System.Environment.GetCommandLineArgs ()</span><br><span class="line"> <span class="keyword">let</span> usageGetter () <span class="operator">=</span> <span class="string">"[Usage]\n %p %o"</span></span><br><span class="line"> <span class="keyword">try</span></span><br><span class="line"> <span class="keyword">let</span> left, opts <span class="operator">=</span> optParse spec usageGetter prog args defaultOpts</span><br><span class="line"> <span class="built_in">printfn</span> <span class="string">"Rest args: %A, x: %d, y: %b, z: %s"</span></span><br><span class="line"> left opts.optX opts.optY opts.optZ</span><br><span class="line"> <span class="number">0</span></span><br><span class="line"> <span class="keyword">with</span></span><br><span class="line"> <span class="operator">|</span> SpecErr msg <span class="operator">-></span></span><br><span class="line"> <span class="built_in">eprintfn</span> <span class="string">"Invalid spec: %s"</span> msg</span><br><span class="line"> exit <span class="number">1</span></span><br><span class="line"> <span class="operator">|</span> RuntimeErr msg <span class="operator">-></span></span><br><span class="line"> <span class="built_in">eprintfn</span> <span class="string">"Invalid args given by user: %s"</span> msg</span><br><span class="line"> usagePrint spec prog usageGetter (<span class="keyword">fun</span> () <span class="operator">-></span> exit <span class="number">1</span>)</span><br></pre></td></tr></table></figure> @@ -974,24 +956,25 @@ await prisma.$transaction(async tx => { <entry> <title>OCaml Core.Int.pow 的实现</title> <url>/2023/10/21/OCaml-Core-Int-pow-%E7%9A%84%E5%AE%9E%E7%8E%B0/</url> - <content><![CDATA[<p>Core内部直接引用的Base的实现, Base的实现在 <a href="https://github.com/janestreet/base/blob/494a0876168d24cda695cbb9a3d86ad8d1eb97d8/src/int_math.ml#L11-L18">src/int_math.ml</a> 中:</p> + <content><![CDATA[<p>Core内部直接引用的Base的实现, Base的实现在 <a href="https://github.com/janestreet/base/blob/494a0876168d24cda695cbb9a3d86ad8d1eb97d8/src/int_math.ml#L11-L18">src/int_math.ml</a> 中:</p> <figure class="highlight ocaml"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> int_pow base exponent =</span><br><span class="line"> <span class="keyword">if</span> exponent < <span class="number">0</span> <span class="keyword">then</span> negative_exponent <span class="literal">()</span>;</span><br><span class="line"> <span class="keyword">if</span> abs base > <span class="number">1</span></span><br><span class="line"> && (exponent > <span class="number">63</span></span><br><span class="line"> || abs base > <span class="type">Pow_overflow_bounds</span>.int_positive_overflow_bounds.(exponent))</span><br><span class="line"> <span class="keyword">then</span> overflow <span class="literal">()</span>;</span><br><span class="line"> int_math_int_pow base exponent</span><br><span class="line">;;</span><br></pre></td></tr></table></figure> - <p>其中 <code>int_math_int_pow()</code> 由 C 实现:</p> <figure class="highlight ocaml"><table><tr><td class="code"><pre><span class="line"><span class="keyword">external</span> int_math_int_pow : <span class="built_in">int</span> -> <span class="built_in">int</span> -> <span class="built_in">int</span> = <span class="string">"Base_int_math_int_pow_stub"</span> [@@noalloc]</span><br></pre></td></tr></table></figure> - -<p>其实现在 <a href="https://github.com/janestreet/base/blob/494a0876168d24cda695cbb9a3d86ad8d1eb97d8/src/int_math_stubs.c#L56-L92">src/int_math_stubs.c</a> 中:</p> +<p>其实现在 <a href="https://github.com/janestreet/base/blob/494a0876168d24cda695cbb9a3d86ad8d1eb97d8/src/int_math_stubs.c#L56-L92">src/int_math_stubs.c</a> 中:</p> <figure class="highlight c"><table><tr><td class="code"><pre><span class="line"><span class="type">static</span> <span class="type">int64_t</span> <span class="title function_">int_pow</span><span class="params">(<span class="type">int64_t</span> base, <span class="type">int64_t</span> exponent)</span> {</span><br><span class="line"> <span class="type">int64_t</span> ret = <span class="number">1</span>;</span><br><span class="line"> <span class="type">int64_t</span> mul[<span class="number">4</span>];</span><br><span class="line"> mul[<span class="number">0</span>] = <span class="number">1</span>;</span><br><span class="line"> mul[<span class="number">1</span>] = base;</span><br><span class="line"> mul[<span class="number">3</span>] = <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">while</span> (exponent != <span class="number">0</span>) {</span><br><span class="line"> mul[<span class="number">1</span>] *= mul[<span class="number">3</span>];</span><br><span class="line"> mul[<span class="number">2</span>] = mul[<span class="number">1</span>] * mul[<span class="number">1</span>];</span><br><span class="line"> mul[<span class="number">3</span>] = mul[<span class="number">2</span>] * mul[<span class="number">1</span>];</span><br><span class="line"> ret *= mul[exponent & <span class="number">3</span>];</span><br><span class="line"> exponent >>= <span class="number">2</span>;</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="keyword">return</span> ret;</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - -<p>这是一个四分快速幂的实现,它是二分快速幂的一种变种。二分快速幂将指数分为两部分,然后递归地计算每一部分的结果。<br>而四分快速幂将指数分为四部分,然后递归地计算每一部分的结果。<br>这里通过将指数右移2位(相当于除以4)和使用位与操作来实现,进一步减少了乘法次数。</p> +<p>这是一个四分快速幂的实现,它是二分快速幂的一种变种。二分快速幂将指数分为两部分,然后递归地计算每一部分的结果。<br> +而四分快速幂将指数分为四部分,然后递归地计算每一部分的结果。<br> +这里通过将指数右移2位(相当于除以4)和使用位与操作来实现,进一步减少了乘法次数。</p> <p>主要步骤:</p> <ul> <li>初始化返回值ret为1,和一个包含4个元素的数组mul, mul[0]和mul[3]被初始化为1, mul[1]被初始化为基数</li> -<li>当指数不为0时,执行循环, 在每次循环中,首先更新mul数组的值<blockquote> +<li>当指数不为0时,执行循环, 在每次循环中,首先更新mul数组的值 +<blockquote> <p>mul[1]是基数和mul[3]的乘积,mul[2]是mul[1]的平方,mul[3]是mul[2]和基数的乘积</p> </blockquote> </li> -<li>然后,将ret乘以mul数组中的一个元素, 这个元素的索引是指数和3的位与运算的结果<blockquote> +<li>然后,将ret乘以mul数组中的一个元素, 这个元素的索引是指数和3的位与运算的结果 +<blockquote> <p>这样做的目的是为了选择正确的乘数,因为指数被分解为4的倍数</p> </blockquote> </li> @@ -1007,7 +990,8 @@ await prisma.$transaction(async tx => { <entry> <title>OCaml News 2024-1</title> <url>/2024/01/08/OCaml-News-2024-1/</url> - <content><![CDATA[<h2 id="News"><a href="#News" class="headerlink" title="News"></a>News</h2><ul> + <content><![CDATA[<h2 id="News"><a class="header-anchor" href="#News">¶</a>News</h2> +<ul> <li><a href="https://tarides.com/blog/2023-12-20-ocaml-survey-developers-perception-interest-and-perceived-barriers/">OCaml Survey: Developers’ Perception, Interest, and Perceived Barriers</a></li> <li><a href="https://tarides.com/blog/2023-12-29-announcing-the-orchide-project-powering-satellite-innovation/">Announcing the ORCHIDE Project: Powering Satellite Innovation</a></li> <li><a href="https://github.com/ocaml/ocaml/pull/12885">Dynarrays, unboxed (with local dummies) #12885</a></li> @@ -1018,13 +1002,15 @@ await prisma.$transaction(async tx => { <li><a href="https://github.com/ocaml/ocaml/pull/1802">Make the character set for OCaml source code officially UTF-8. #1802</a></li> <li><a href="https://github.com/ocaml/ocaml/pull/12719">Add thread local storage #12719</a></li> </ul> -<h2 id="Videos"><a href="#Videos" class="headerlink" title="Videos"></a>Videos</h2><ul> +<h2 id="Videos"><a class="header-anchor" href="#Videos">¶</a>Videos</h2> +<ul> <li><a href="https://www.youtube.com/watch?v=zG7JejHlQoM">“Melange: The next frontier in type-safe web development” by Dillon Mulroy - RVAJS 2023</a></li> <li><a href="https://www.youtube.com/watch?v=R-XJzUrP7bQ">Trying out OCaml TUI framework Mint Tea!</a></li> <li><a href="https://www.youtube.com/watch?v=XyDbG9FGR1o">A TUI chat in OCaml 🐫</a></li> <li>[Building a Game Engine… with OCaml ?! [Part 1]](<a href="https://www.youtube.com/watch?v=1XpUaTnssQE">https://www.youtube.com/watch?v=1XpUaTnssQE</a></li> </ul> -<h2 id="Blogs"><a href="#Blogs" class="headerlink" title="Blogs"></a>Blogs</h2><ul> +<h2 id="Blogs"><a class="header-anchor" href="#Blogs">¶</a>Blogs</h2> +<ul> <li><a href="https://sancho.dev/blog/whats-possible-with-melange">What’s possible with Melange</a></li> <li><a href="https://discuss.ocaml.org/t/access-inferred-types/13805">Access inferred types</a></li> <li><a href="https://discuss.ocaml.org/t/using-menhir-to-parse-into-idiomatic-js-typescript-structures/13809">Using Menhir to parse into idiomatic JS (TypeScript) structures</a></li> @@ -1034,7 +1020,8 @@ await prisma.$transaction(async tx => { <li><a href="https://discuss.ocaml.org/t/how-to-express-koka-home-page-example/13748">How to express Koka home page example?</a></li> <li><a href="https://practicalocaml.com/parsing-with-binary-string-pattern-matching/">Parsing with Binary String Pattern Matching</a></li> </ul> -<h2 id="Highlighted-Projects"><a href="#Highlighted-Projects" class="headerlink" title="Highlighted Projects"></a>Highlighted Projects</h2><ul> +<h2 id="Highlighted-Projects"><a class="header-anchor" href="#Highlighted-Projects">¶</a>Highlighted Projects</h2> +<ul> <li><a href="https://github.com/backtracking/grid">grid: A tiny library for two-dimensional arrays</a></li> <li><a href="https://github.com/leostera/minttea">A fun little TUI framework for OCaml</a></li> <li><a href="https://github.com/terrateamio/ocaml-ts-mode">ocaml-ts-mode: Ocaml mode for emacs using treesitter</a></li> @@ -1047,11 +1034,12 @@ await prisma.$transaction(async tx => { <li><a href="https://github.com/leostera/colors">colors: A pure OCaml library for manipulating colors in different color spaces.</a></li> <li><a href="https://github.com/nationalarchives/miiify">miilfy: A web annotation server built with the same principles as Git</a></li> </ul> -<h2 id="New-Releases"><a href="#New-Releases" class="headerlink" title="New Releases"></a>New Releases</h2><ul> +<h2 id="New-Releases"><a class="header-anchor" href="#New-Releases">¶</a>New Releases</h2> +<ul> <li><a href="https://github.com/leostera/riot">Roit v0.0.7: An actor-model multi-core scheduler for OCaml 5 🐫</a></li> -<li><a href="https://github.com/leostera/castore">CAStore: A portable pure OCaml CA Store, with no dependencies, inspired by Elixir’s <a href="https://github.com/elixir-mint/castore">:castore</a>.</a></li> +<li>[CAStore: A portable pure OCaml CA Store, with no dependencies, inspired by Elixir’s <a href="https://github.com/elixir-mint/castore">:castore</a>.](<a href="https://github.com/leostera/castore">https://github.com/leostera/castore</a>)</li> <li><a href="https://discuss.ocaml.org/t/learn-ocaml-1-0-approaching-call-for-testers/13621">Lean-OCaml 1.0: A Web Application for Learning OCaml</a></li> -<li><a href="https://erratique.ch/software/cmarkit">cmarkit 0.3.0” CommonMark parser and renderer for OCaml</a></li> +<li><a href="https://erratique.ch/software/cmarkit">cmarkit 0.3.0" CommonMark parser and renderer for OCaml</a></li> <li><a href="https://ocaml.org/p/dream-html/latest">dream-html 2.0.0: A library for generating HTML</a></li> <li><a href="https://git.frama-c.com/pub/caisar/">Caisar: A platform under active development at CEA LIST, aiming to provide a wide range of features to characterize the safety and robustness of artificial intelligence based software.</a></li> <li><a href="https://github.com/jserot/rfsm">RFSM 2.0: A toolset for describing and simulating StateChart-like state diagrams.</a></li> @@ -1065,16 +1053,18 @@ await prisma.$transaction(async tx => { <entry> <title>OCaml News 2024-2</title> <url>/2024/01/18/OCaml-News-2024-2/</url> - <content><![CDATA[<h2 id="News"><a href="#News" class="headerlink" title="News"></a>News</h2><ul> + <content><![CDATA[<h2 id="News"><a class="header-anchor" href="#News">¶</a>News</h2> +<ul> <li><a href="https://discuss.ocaml.org/t/ann-preview-play-with-project-wide-occurrences-for-ocaml/13814">[ANN][PREVIEW] Play with project-wide occurrences for OCaml!</a></li> <li><a href="https://github.com/ocaml/dune/pull/8784">[Dune]: Add link flags ocamlmklib when using ctypes stubs. #8784</a></li> <li><a href="https://discuss.ocaml.org/t/ocaml-software-foundation-january-2024-update/13828">OCaml Software Foundation: January 2024 update</a></li> <li>[Apprendre à programmer avec OCaml](Apprendre à programmer avec OCaml)</li> -<li><a href="https://discuss.ocaml.org/t/call-for-speakers-for-the-2024-carolina-code-conference-is-open-until-april-15th/13827"><a href="https://discuss.ocaml.org/t/call-for-speakers-for-the-2024-carolina-code-conference-is-open-until-april-15th/13827">Call for Speakers for the 2024 Carolina Code Conference is open until April 15th</a></a></li> +<li>[<a href="https://discuss.ocaml.org/t/call-for-speakers-for-the-2024-carolina-code-conference-is-open-until-april-15th/13827">Call for Speakers for the 2024 Carolina Code Conference is open until April 15th</a>](<a href="https://discuss.ocaml.org/t/call-for-speakers-for-the-2024-carolina-code-conference-is-open-until-april-15th/13827">https://discuss.ocaml.org/t/call-for-speakers-for-the-2024-carolina-code-conference-is-open-until-april-15th/13827</a>)</li> <li><a href="https://github.com/ocaml/ocaml/discussions/11924">[OCaml]: feature request: better errors #11924</a></li> <li><a href="https://discuss.ocaml.org/t/ocsigen-summary-of-recent-releases/13817">Ocsigen: summary of recent releases</a></li> </ul> -<h2 id="Discussion"><a href="#Discussion" class="headerlink" title="Discussion"></a>Discussion</h2><ul> +<h2 id="Discussion"><a class="header-anchor" href="#Discussion">¶</a>Discussion</h2> +<ul> <li><a href="https://discuss.ocaml.org/t/benchmark-between-open-addressing-and-closed-addressing-hashtbl/13882">Benchmark between open-addressing and closed-addressing hashtbl</a></li> <li><a href="https://discuss.ocaml.org/t/examples-of-caqti-infix/13878">Examples of Caqti infix?</a></li> <li><a href="https://discuss.ocaml.org/t/why-can-t-i-create-a-project-with-non-ascii-characters/13865">Why can’t I create a project with non-ASCII characters? </a></li> @@ -1084,20 +1074,23 @@ await prisma.$transaction(async tx => { <li><a href="https://discuss.ocaml.org/t/partially-apply-function-accepting-multiple-modules-and-keep-polymorphic-types/13823">Partially apply function accepting multiple modules and keep polymorphic types</a></li> <li><a href="https://discuss.ocaml.org/t/printing-unicode-characters-on-different-platforms/13813">Printing Unicode Characters on Different Platforms</a></li> </ul> -<h2 id="Videos"><a href="#Videos" class="headerlink" title="Videos"></a>Videos</h2><ul> +<h2 id="Videos"><a class="header-anchor" href="#Videos">¶</a>Videos</h2> +<ul> <li><a href="https://watch.ocaml.org/w/iQNqZzA8gVmd4RQaycAwx4">Verifying an Effect-Based Cooperative Concurrency Scheduler in Iris by Adrian Dapprich</a></li> </ul> -<h2 id="Blogs"><a href="#Blogs" class="headerlink" title="Blogs"></a>Blogs</h2><ul> +<h2 id="Blogs"><a class="header-anchor" href="#Blogs">¶</a>Blogs</h2> +<ul> <li><a href="https://discuss.ocaml.org/t/advice-for-combining-multiple-monads/10409">Advice for combining multiple monads</a></li> <li><a href="https://discuss.ocaml.org/t/writing-ctypes-bindings-to-system-shared-libraries-for-bytecode-targets-via-the-dune-ctypes-stanza/13844">Writing ctypes bindings to system shared libraries for bytecode targets via the dune ctypes stanza</a></li> </ul> -<h2 id="Highlighted-Projects"><a href="#Highlighted-Projects" class="headerlink" title="Highlighted Projects"></a>Highlighted Projects</h2><ul> +<h2 id="Highlighted-Projects"><a class="header-anchor" href="#Highlighted-Projects">¶</a>Highlighted Projects</h2> +<ul> <li><a href="https://github.com/johnyob/grace">Grace: A fancy diagnostics library that allows your compilers to exit with grace</a></li> <li><a href="https://github.com/thierry-martinez/metapp">meta-pp: Meta-preprocessor for OCaml</a></li> <li><a href="https://github.com/stedolan/ppx_stage">ppx_stage: Staged metaprogramming in stock OCaml</a></li> -<li><a href="https://erratique.ch/software/cmarkit">Cmarkit is an <a href="http://ocaml.org/">OCaml</a> libary for parsing the <a href="https://spec.commonmark.org/">CommonMark</a> specification.</a></li> -<li><a href="https://erratique.ch/software/brr">Brr is a toolkit for programming browsers in <a href="http://ocaml.org/">OCaml</a> with the <a href="http://ocsigen.org/js_of_ocaml/">js_of_ocaml</a> compiler. It provides:</a></li> -<li><a href="https://erratique.ch/software/zipc">Zipc is an in-memory <a href="https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT">ZIP</a> archive and <a href="https://www.rfc-editor.org/rfc/rfc1951">deflate</a> compression codec for <a href="http://ocaml.org/">OCaml</a>.</a></li> +<li>[Cmarkit is an <a href="http://ocaml.org">OCaml</a> libary for parsing the <a href="https://spec.commonmark.org/">CommonMark</a> specification.](<a href="https://erratique.ch/software/cmarkit">https://erratique.ch/software/cmarkit</a>)</li> +<li>[Brr is a toolkit for programming browsers in <a href="http://ocaml.org">OCaml</a> with the <a href="http://ocsigen.org/js_of_ocaml/">js_of_ocaml</a> compiler. It provides:](<a href="https://erratique.ch/software/brr">https://erratique.ch/software/brr</a>)</li> +<li>[Zipc is an in-memory <a href="https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT">ZIP</a> archive and <a href="https://www.rfc-editor.org/rfc/rfc1951">deflate</a> compression codec for <a href="http://ocaml.org">OCaml</a>.](<a href="https://erratique.ch/software/zipc">https://erratique.ch/software/zipc</a>)</li> <li><a href="https://github.com/lukstafi/ocaml-gccjit">ocaml-gccjit: OCaml bindings for libgccjit</a></li> <li><a href="https://github.com/whitequark/ocaml-m17n">ocaml-m17n: Multilingualization for the OCaml source code</a></li> <li><a href="https://github.com/hackwaly/ocamlearlybird">ocamlearlybird: OCaml debug adapter</a></li> @@ -1105,21 +1098,26 @@ await prisma.$transaction(async tx => { <li><a href="https://github.com/mattjbray/ocaml-decoders">ocaml-decoders: Elm-inspired decoders for Ocaml</a></li> <li><a href="https://github.com/OCamlPro/ez_toml">ez_toml: A library to parse and print TOML files</a></li> </ul> -<h2 id="New-Releases"><a href="#New-Releases" class="headerlink" title="New Releases"></a>New Releases</h2><ul> -<li><a href="http://cambium.inria.fr/~fpottier/oma/doc/oma/Oma/index.html">Oma: OCaml implementation of ‘Two Simplified Algorithms for Maintaining Order in a List’</a><ul> +<h2 id="New-Releases"><a class="header-anchor" href="#New-Releases">¶</a>New Releases</h2> +<ul> +<li><a href="http://cambium.inria.fr/~fpottier/oma/doc/oma/Oma/index.html">Oma: OCaml implementation of ‘Two Simplified Algorithms for Maintaining Order in a List’</a> +<ul> <li><a href="https://discuss.ocaml.org/t/ann-first-release-of-oma/13845">[ANN] First release of oma</a></li> <li><a href="https://erikdemaine.org/papers/DietzSleator_ESA2002/paper.pdf">Two Simplified Algorithms for Maintaining Order in a List</a></li> </ul> </li> -<li><a href="https://github.com/hackwaly/ocamlearlybird">ocamlearlybird: v1.3.0</a><ul> -<li><a href="https://discuss.ocaml.org/t/ann-ocamlearlybird-just-got-ability-to-inspect-opaque-abstract-values/13852">[ANN] Ocamlearlybird just got ability to inspect opaque/abstract values</a></li> +<li><a href="https://github.com/hackwaly/ocamlearlybird">ocamlearlybird: v1.3.0</a> +<ul> +<li><a href="https://discuss.ocaml.org/t/ann-ocamlearlybird-just-got-ability-to-inspect-opaque-abstract-values/13852">[ANN] Ocamlearlybird just got ability to inspect opaque/abstract values</a></li> </ul> </li> -<li><a href="https://github.com/Axot017/validate">validate: OCaml Data Validation library</a><ul> +<li><a href="https://github.com/Axot017/validate">validate: OCaml Data Validation library</a> +<ul> <li><a href="https://discuss.ocaml.org/t/ann-validate-a-new-library-for-data-validation/13861">[ANN] Validate - A New Library for Data Validation</a></li> </ul> </li> -<li><a href="https://github.com/gborough/sarif">sarif v2.1.0: Static Analysis Results Interchange Format (SARIF) For OCaml</a><ul> +<li><a href="https://github.com/gborough/sarif">sarif v2.1.0: Static Analysis Results Interchange Format (SARIF) For OCaml</a> +<ul> <li><a href="https://discuss.ocaml.org/t/ann-sarif-0-1-0-static-analysis-results-interchange-format-sarif-for-ocaml/13821">[ANN] sarif 0.1.0 - Static Analysis Results Interchange Format (SARIF) For OCaml</a></li> </ul> </li> @@ -1133,99 +1131,144 @@ await prisma.$transaction(async tx => { <entry> <title>OCaml News 2024-3</title> <url>/2024/02/26/OCaml-News-2024-3/</url> - <content><![CDATA[<h2 id=""><a href="#" class="headerlink" title=""></a></h2><p>o-新鲜事儿</p> + <content><![CDATA[<h2 id=""><a class="header-anchor" href="#">¶</a></h2> +<p>o-新鲜事儿</p> <ul> -<li><p><a href="https://discuss.ocaml.org/t/ocaml-5-1-0-released/13021">OCaml 5.1.0 released</a></p> +<li> +<p><a href="https://discuss.ocaml.org/t/ocaml-5-1-0-released/13021">OCaml 5.1.0 released</a></p> </li> -<li><p><a href="https://discuss.ocaml.org/t/ann-dune-3-14/14096">[ANN] dune 3.14</a></p> +<li> +<p><a href="https://discuss.ocaml.org/t/ann-dune-3-14/14096">[ANN] dune 3.14</a></p> </li> -<li><p><a href="https://ocaml.codes/search/">code search</a></p> +<li> +<p><a href="https://ocaml.codes/search/">code search</a></p> </li> -<li><p><a href="https://discuss.ocaml.org/t/ann-ocaml-codes-code-search-for-opam-packages/14092">[ANN] ocaml.codes, code search for OPAM packages</a></p> +<li> +<p><a href="https://discuss.ocaml.org/t/ann-ocaml-codes-code-search-for-opam-packages/14092">[ANN] ocaml.codes, code search for OPAM packages</a></p> </li> -<li><p>用 livegrep 基于 opam 包的源码做的代码搜索,还挺方便的。</p> +<li> +<p>用 livegrep 基于 opam 包的源码做的代码搜索,还挺方便的。</p> </li> -<li><p><a href="https://melange.re/blog/posts/announcing-melange-3">Announcing Melange 3</a></p> +<li> +<p><a href="https://melange.re/blog/posts/announcing-melange-3">Announcing Melange 3</a></p> </li> -<li><p><a href="https://discuss.ocaml.org/t/ann-melange-3-0/14102">[ANN] Melange 3.0</a></p> +<li> +<p><a href="https://discuss.ocaml.org/t/ann-melange-3-0/14102">[ANN] Melange 3.0</a></p> </li> -<li><p><a href="https://discuss.ocaml.org/t/learn-ocaml-1-0-is-out/14100">Learn-OCaml 1.0 is out!</a></p> +<li> +<p><a href="https://discuss.ocaml.org/t/learn-ocaml-1-0-is-out/14100">Learn-OCaml 1.0 is out!</a></p> </li> -<li><p><a href="https://ocaml-sf.org/learn-ocaml-public/">https://ocaml-sf.org/learn-ocaml-public/</a></p> +<li> +<p><a href="https://ocaml-sf.org/learn-ocaml-public/">https://ocaml-sf.org/learn-ocaml-public/</a></p> </li> -<li><p><a href="https://github.com/owlbarn/owl">GitHub - owlbarn/owl: Owl - OCaml Scientific Computing @ http://ocaml.xyz</a></p> +<li> +<p><a href="https://github.com/owlbarn/owl">GitHub - owlbarn/owl: Owl - OCaml Scientific Computing @ http://ocaml.xyz</a></p> </li> -<li><p><a href="https://discuss.ocaml.org/t/owl-project-concluding/14117">Owl project concluding</a></p> +<li> +<p><a href="https://discuss.ocaml.org/t/owl-project-concluding/14117">Owl project concluding</a></p> </li> -<li><p>经过八年的维护,Owl项目即将终止</p> +<li> +<p>经过八年的维护,Owl项目即将终止</p> </li> </ul> -<h2 id="-1"><a href="#-1" class="headerlink" title=""></a></h2><p>o-视频</p> +<h2 id="-v2"><a class="header-anchor" href="#-v2">¶</a></h2> +<p>o-视频</p> <ul> -<li><p><a href="https://www.youtube.com/watch?v=jvQ7fj9LlVA">Inferring Locality in OCaml | OCaml Unboxed</a></p> +<li> +<p><a href="https://www.youtube.com/watch?v=jvQ7fj9LlVA">Inferring Locality in OCaml | OCaml Unboxed</a></p> </li> -<li><p><a href="https://www.youtube.com/watch?v=AGu4AO5zO8o">OCaml Locals Save Allocations | OCaml Unboxed</a></p> +<li> +<p><a href="https://www.youtube.com/watch?v=AGu4AO5zO8o">OCaml Locals Save Allocations | OCaml Unboxed</a></p> </li> -<li><p><a href="https://watch.ocaml.org/w/qQzb94X9WM7zLif7FynPyN">Ocsigen: Developing Web and mobile applications in OCaml – Jérôme Vouillon & Vincent Balat</a></p> +<li> +<p><a href="https://watch.ocaml.org/w/qQzb94X9WM7zLif7FynPyN">Ocsigen: Developing Web and mobile applications in OCaml – Jérôme Vouillon & Vincent Balat</a></p> </li> -<li><p><a href="https://watch.ocaml.org/w/iQNqZzA8gVmd4RQaycAwx4">Verifying an Effect-Based Cooperative Concurrency Scheduler in Iris by Adrian Dapprich</a></p> +<li> +<p><a href="https://watch.ocaml.org/w/iQNqZzA8gVmd4RQaycAwx4">Verifying an Effect-Based Cooperative Concurrency Scheduler in Iris by Adrian Dapprich</a></p> </li> </ul> -<h2 id="-2"><a href="#-2" class="headerlink" title=""></a></h2><p>o-博客 / 文章 / 帖子</p> +<h2 id="-v3"><a class="header-anchor" href="#-v3">¶</a></h2> +<p>o-博客 / 文章 / 帖子</p> <ul> -<li><p><a href="https://priver.dev/blog/dbcaml/dbcaml/">Introducing DBCaml, Database toolkit for OCaml</a></p> +<li> +<p><a href="https://priver.dev/blog/dbcaml/dbcaml/">Introducing DBCaml, Database toolkit for OCaml</a></p> </li> -<li><p><a href="https://priver.dev/blog/dbcaml/building-a-connnection-pool/">Building a Connnection Pool for DBCaml on top of riot</a></p> +<li> +<p><a href="https://priver.dev/blog/dbcaml/building-a-connnection-pool/">Building a Connnection Pool for DBCaml on top of riot</a></p> </li> -<li><p><a href="https://ocamlpro.com/blog/2021_09_02_generating_static_and_portable_executables_with_ocaml/">Generating static and portable executables with OCaml</a></p> +<li> +<p><a href="https://ocamlpro.com/blog/2021_09_02_generating_static_and_portable_executables_with_ocaml/">Generating static and portable executables with OCaml</a></p> </li> -<li><p>OCaml编译器没有内置生成静态可移植可执行文件的特性,这里提到了一些技巧</p> +<li> +<p>OCaml编译器没有内置生成静态可移植可执行文件的特性,这里提到了一些技巧</p> </li> -<li><p><a href="https://discuss.ocaml.org/t/analog-of-promise-any-for-multicore-ocaml/14145">Analog of Promise.any() for Multicore OCaml</a></p> +<li> +<p><a href="https://discuss.ocaml.org/t/analog-of-promise-any-for-multicore-ocaml/14145">Analog of Promise.any() for Multicore OCaml</a></p> </li> -<li><p><a href="https://discuss.ocaml.org/t/printf-vs-format/14130">Printf vs. Format?</a></p> +<li> +<p><a href="https://discuss.ocaml.org/t/printf-vs-format/14130">Printf vs. Format?</a></p> </li> -<li><p><a href="https://discuss.ocaml.org/t/how-to-represent-tuples-in-ast/14095">How to represent tuples in AST?</a></p> +<li> +<p><a href="https://discuss.ocaml.org/t/how-to-represent-tuples-in-ast/14095">How to represent tuples in AST?</a></p> </li> -<li><p><a href="https://discuss.ocaml.org/t/how-do-i-pass-an-unsigned-char-an-array-of-bytes-representing-binary-data-from-c-to-ocaml/14074">How do I pass an unsigned char * (an array of bytes representing binary data) from C to OCaml?</a></p> +<li> +<p><a href="https://discuss.ocaml.org/t/how-do-i-pass-an-unsigned-char-an-array-of-bytes-representing-binary-data-from-c-to-ocaml/14074">How do I pass an unsigned char * (an array of bytes representing binary data) from C to OCaml?</a></p> </li> </ul> -<h2 id="-3"><a href="#-3" class="headerlink" title=""></a></h2><p>o-未来</p> +<h2 id="-v4"><a class="header-anchor" href="#-v4">¶</a></h2> +<p>o-未来</p> <ul> -<li><p><a href="https://docs.google.com/forms/d/e/1FAIpQLSe1U_5KanTeKt1h9t5vjYohYXepXDhPCru4tsms4OcI5k0Fkw/viewform?pli=1">How do we want to present OCaml to the World on OCaml.org?</a></p> +<li> +<p><a href="https://docs.google.com/forms/d/e/1FAIpQLSe1U_5KanTeKt1h9t5vjYohYXepXDhPCru4tsms4OcI5k0Fkw/viewform?pli=1">How do we want to present OCaml to the World on OCaml.org?</a></p> </li> -<li><p>一个问卷,用于更好的改进 <a href="http://ocaml.org/">ocaml.org</a> 有关学术和工业应用板块的内容。</p> +<li> +<p>一个问卷,用于更好的改进 <a href="http://ocaml.org/">ocaml.org</a> 有关学术和工业应用板块的内容。</p> </li> -<li><p><a href="https://discuss.ocaml.org/t/feedback-help-wanted-upcoming-ocaml-org-cookbook-feature/14127">Feedback / Help Wanted: Upcoming OCaml.org Cookbook Feature</a></p> +<li> +<p><a href="https://discuss.ocaml.org/t/feedback-help-wanted-upcoming-ocaml-org-cookbook-feature/14127">Feedback / Help Wanted: Upcoming OCaml.org Cookbook Feature</a></p> </li> -<li><p><a href="http://ocaml.org/">ocaml.org</a> 准备上线一个cookbook页面,放一些如何用OCaml的生态解决常见需求的资源</p> +<li> +<p><a href="http://ocaml.org/">ocaml.org</a> 准备上线一个cookbook页面,放一些如何用OCaml的生态解决常见需求的资源</p> </li> -<li><p><a href="https://discuss.ocaml.org/t/state-of-compaction-in-ocaml-5/14121/1">State of compaction in OCaml 5?</a></p> +<li> +<p><a href="https://discuss.ocaml.org/t/state-of-compaction-in-ocaml-5/14121/1">State of compaction in OCaml 5?</a></p> </li> -<li><p>OCaml 5.2 的 compact heap 会将未使用的内存返回给操作系统。在 OCaml 5 的 GC 中,小于 128byte 的块用大小隔离池进行管理,比如有一个池,处理大小为 3byte 的分配,另一个池处理大小为 4byte 的分配等等,这样的池在每个Domain里都有。用这个方法分配速度很快,因为不用找合适的内存间隙了,只要找正确的池大小就行。</p> +<li> +<p>OCaml 5.2 的 compact heap 会将未使用的内存返回给操作系统。在 OCaml 5 的 GC 中,小于 128byte 的块用大小隔离池进行管理,比如有一个池,处理大小为 3byte 的分配,另一个池处理大小为 4byte 的分配等等,这样的池在每个Domain里都有。用这个方法分配速度很快,因为不用找合适的内存间隙了,只要找正确的池大小就行。</p> </li> </ul> -<h2 id="-4"><a href="#-4" class="headerlink" title=""></a></h2><p>o-值得被注意的项目</p> +<h2 id="-v5"><a class="header-anchor" href="#-v5">¶</a></h2> +<p>o-值得被注意的项目</p> <ul> -<li><p><a href="https://github.com/mbarbin/vcs">GitHub - mbarbin/vcs: A versatile OCaml library for Git interaction</a></p> +<li> +<p><a href="https://github.com/mbarbin/vcs">GitHub - mbarbin/vcs: A versatile OCaml library for Git interaction</a></p> </li> -<li><p><a href="https://discuss.ocaml.org/t/a-versatile-ocaml-library-for-git-interaction-seeking-community-feedback/14155">A Versatile OCaml Library for Git Interaction - Seeking Community Feedback</a></p> +<li> +<p><a href="https://discuss.ocaml.org/t/a-versatile-ocaml-library-for-git-interaction-seeking-community-feedback/14155">A Versatile OCaml Library for Git Interaction - Seeking Community Feedback</a></p> </li> -<li><p><a href="https://github.com/dbcaml/dbcaml">GitHub - dbcaml/dbcaml: DBCaml is a database library for OCaml</a></p> +<li> +<p><a href="https://github.com/dbcaml/dbcaml">GitHub - dbcaml/dbcaml: DBCaml is a database library for OCaml</a></p> </li> -<li><p><a href="https://discuss.ocaml.org/t/dbcaml-a-new-database-toolkit-built-on-riot/14150">DBcaml, a new database toolkit built on Riot</a></p> +<li> +<p><a href="https://discuss.ocaml.org/t/dbcaml-a-new-database-toolkit-built-on-riot/14150">DBcaml, a new database toolkit built on Riot</a></p> </li> -<li><p><a href="https://github.com/c-cube/fuseau">GitHub - c-cube/fuseau: [alpha] lightweight fiber library for OCaml 5</a></p> +<li> +<p><a href="https://github.com/c-cube/fuseau">GitHub - c-cube/fuseau: [alpha] lightweight fiber library for OCaml 5</a></p> </li> -<li><p><a href="https://discuss.ocaml.org/t/ann-fuseau-0-1/14157">[ANN] fuseau 0.1</a></p> +<li> +<p><a href="https://discuss.ocaml.org/t/ann-fuseau-0-1/14157">[ANN] fuseau 0.1</a></p> </li> -<li><p><a href="https://github.com/issuu/ocaml-protoc-plugin">GitHub - issuu/ocaml-protoc-plugin: ocaml-protoc-plugin</a></p> +<li> +<p><a href="https://github.com/issuu/ocaml-protoc-plugin">GitHub - issuu/ocaml-protoc-plugin: ocaml-protoc-plugin</a></p> </li> -<li><p><a href="https://discuss.ocaml.org/t/taking-over-maintanence-of-a-stale-project/14156">Taking over maintanence of a stale project</a></p> +<li> +<p><a href="https://discuss.ocaml.org/t/taking-over-maintanence-of-a-stale-project/14156">Taking over maintanence of a stale project</a></p> </li> -<li><p><a href="https://github.com/darrenldl/docfd">GitHub - darrenldl/docfd: TUI multiline fuzzy document finder</a></p> +<li> +<p><a href="https://github.com/darrenldl/docfd">GitHub - darrenldl/docfd: TUI multiline fuzzy document finder</a></p> </li> -<li><p><a href="https://discuss.ocaml.org/t/ann-docfd-tui-multiline-fuzzy-document-finder-2-2-0/14109/1">[ANN] Docfd: TUI multiline fuzzy document finder 2.2.0</a></p> +<li> +<p><a href="https://discuss.ocaml.org/t/ann-docfd-tui-multiline-fuzzy-document-finder-2-2-0/14109/1">[ANN] Docfd: TUI multiline fuzzy document finder 2.2.0</a></p> </li> </ul> ]]></content> @@ -1236,115 +1279,167 @@ await prisma.$transaction(async tx => { <entry> <title>OCaml News 2024-4</title> <url>/2024/07/01/OCaml-News-2024-4/</url> - <content><![CDATA[<h2 id="那么接下来"><a href="#那么接下来" class="headerlink" title="那么接下来"></a>那么接下来</h2><ul> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/first-beta-release-for-ocaml-5-2-0/14356">First beta release for OCaml 5.2.0</a>.</p> + <content><![CDATA[<h2 id="那么接下来"><a class="header-anchor" href="#那么接下来">¶</a>那么接下来</h2> +<ul> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/first-beta-release-for-ocaml-5-2-0/14356">First beta release for OCaml 5.2.0</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/issues/12876">#12876</a> 和 <a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/issues/12915">#12915</a> 提供了 ThreadSanitizer 对 Power 和 s390x 上的 Linux 支持。</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/issues/12876">#12876</a> 和 <a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/issues/12915">#12915</a> 提供了 ThreadSanitizer 对 Power 和 s390x 上的 Linux 支持。</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/issues/12677">#12677</a> 和 <a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/issues/12889">#12889</a> 实现了 <code>Domain.DLS</code> 的线程安全。</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/issues/12677">#12677</a> 和 <a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/issues/12889">#12889</a> 实现了 <code>Domain.DLS</code> 的线程安全。</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/issues/12924">#12924</a> 和 <a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/issues/12930">#12930</a> 提到了一个类型系统的错误和其修复方式(merged):</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/issues/12924">#12924</a> 和 <a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/issues/12930">#12930</a> 提到了一个类型系统的错误和其修复方式(merged):</p> </li> </ul> <figure class="highlight ocaml"><table><tr><td class="code"><pre><span class="line"><span class="keyword">module</span> <span class="keyword">type</span> <span class="type">S</span> = <span class="keyword">sig</span></span><br><span class="line"> <span class="keyword">type</span> t [@@immediate]</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> t = (<span class="keyword">module</span> <span class="type">S</span> <span class="keyword">with</span> <span class="keyword">type</span> t = <span class="built_in">int</span>)</span><br><span class="line"> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^</span><br><span class="line"><span class="comment">(*</span></span><br><span class="line"><span class="comment">Error: In this with constraint, the new definition of t</span></span><br><span class="line"><span class="comment"> does not match its original definition in the constrained signature:</span></span><br><span class="line"><span class="comment"> Type declarations do not match:</span></span><br><span class="line"><span class="comment"> type t</span></span><br><span class="line"><span class="comment"> is not included in</span></span><br><span class="line"><span class="comment"> type t [@@immediate]</span></span><br><span class="line"><span class="comment"> The first is not an immediate type.</span></span><br><span class="line"><span class="comment">*)</span></span><br></pre></td></tr></table></figure> - <ul> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ocaml-4-14-2-released/14308">OCaml 4.14.2 released</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ocaml-4-14-2-released/14308">OCaml 4.14.2 released</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/owl-project-restructured/14226">Owl project restructured</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/owl-project-restructured/14226">Owl project restructured</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/your-feedback-needed-on-ocaml-home-page-wireframe/14366">Your Feedback Needed on OCaml Home Page Wireframe!</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/your-feedback-needed-on-ocaml-home-page-wireframe/14366">Your Feedback Needed on OCaml Home Page Wireframe!</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/shape-with-us-the-new-ocaml-org-community-area/14322">Shape with us the New OCaml.org Community Area!</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/shape-with-us-the-new-ocaml-org-community-area/14322">Shape with us the New OCaml.org Community Area!</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ocaml-platform-newsletter-february-2024/14361">OCaml Platform Newsletter: February 2024</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ocaml-platform-newsletter-february-2024/14361">OCaml Platform Newsletter: February 2024</a>.</p> </li> -<li><p>其中值得注意的是:<a href="https://link.zhihu.com/?target=https://ocaml.org/docs/platform-roadmap%23w4-build-a-project">探索 dune 和包管理的集成</a> 和 <a href="https://link.zhihu.com/?target=https://ocaml.org/docs/platform-roadmap%23w5-manage-dependencies">opam 2.2 的 Windows Native support</a>.</p> +<li> +<p>其中值得注意的是:<a href="https://link.zhihu.com/?target=https%3A//ocaml.org/docs/platform-roadmap%23w4-build-a-project">探索 dune 和包管理的集成</a> 和 <a href="https://link.zhihu.com/?target=https%3A//ocaml.org/docs/platform-roadmap%23w5-manage-dependencies">opam 2.2 的 Windows Native support</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ocaml-workshop-2024-at-icfp-announcement-and-call-for-proposals/14371">OCaml Workshop 2024 at ICFP – announcement and call for proposals</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ocaml-workshop-2024-at-icfp-announcement-and-call-for-proposals/14371">OCaml Workshop 2024 at ICFP – announcement and call for proposals</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/volunteers-for-icfp-2024-artifact-evaluation-committee-aec/14355">Volunteers for ICFP 2024 Artifact Evaluation Committee (AEC)</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/volunteers-for-icfp-2024-artifact-evaluation-committee-aec/14355">Volunteers for ICFP 2024 Artifact Evaluation Committee (AEC)</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/odoc-3-0-planning/14360">Odoc 3.0 planning</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/odoc-3-0-planning/14360">Odoc 3.0 planning</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/opam-repository-updated-documentation-retirement-and-call-for-maintainers/14325">Opam-repository: Updated documentation, retirement and call for maintainers</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/opam-repository-updated-documentation-retirement-and-call-for-maintainers/14325">Opam-repository: Updated documentation, retirement and call for maintainers</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/u/kit-ty-kate">kit-ty-kate</a> 退休啦。</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/u/kit-ty-kate">kit-ty-kate</a> 退休啦。</p> </li> </ul> -<h2 id="论文"><a href="#论文" class="headerlink" title="论文"></a>论文</h2><ul> -<li><a href="https://link.zhihu.com/?target=https://jcheminf.biomedcentral.com/articles/10.1186/s13321-019-0332-0">Chemoinformatics and structural bioinformatics in OCaml</a>.</li> +<h2 id="论文"><a class="header-anchor" href="#论文">¶</a>论文</h2> +<ul> +<li><a href="https://link.zhihu.com/?target=https%3A//jcheminf.biomedcentral.com/articles/10.1186/s13321-019-0332-0">Chemoinformatics and structural bioinformatics in OCaml</a>.</li> </ul> -<h2 id="帖子-文章"><a href="#帖子-文章" class="headerlink" title="帖子/文章"></a>帖子/文章</h2><ul> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ocaml-for-building-shared-libraries-how-are-the-ergonomics-and-performance/14352">OCaml for building shared libraries: how are the ergonomics and performance?</a></p> +<h2 id="帖子-文章"><a class="header-anchor" href="#帖子-文章">¶</a>帖子/文章</h2> +<ul> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ocaml-for-building-shared-libraries-how-are-the-ergonomics-and-performance/14352">OCaml for building shared libraries: how are the ergonomics and performance?</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://mccd.space/posts/awk-with-kakoune/">Using Awk in Kakoune to Generate SQL Types for OCaml</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//mccd.space/posts/awk-with-kakoune/">Using Awk in Kakoune to Generate SQL Types for OCaml</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://tarides.com/blog/2024-03-20-eio-1-0-release-introducing-a-new-effects-based-i-o-library-for-ocaml/">Eio 1.0 Release: Introducing a new Effects-Based I/O Library for OCaml</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//tarides.com/blog/2024-03-20-eio-1-0-release-introducing-a-new-effects-based-i-o-library-for-ocaml/">Eio 1.0 Release: Introducing a new Effects-Based I/O Library for OCaml</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/blog-the-flambda2-snippets-by-ocamlpro/14331">[BLOG] The Flambda2 Snippets, by OCamlPro</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/blog-the-flambda2-snippets-by-ocamlpro/14331">[BLOG] The Flambda2 Snippets, by OCamlPro</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://ocamlpro.com/blog/2024_03_18_the_flambda2_snippets_0/">The Flambda2 Snippets, Episode 0</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//ocamlpro.com/blog/2024_03_18_the_flambda2_snippets_0/">The Flambda2 Snippets, Episode 0</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://ocamlpro.com/blog/2024_03_19_the_flambda2_snippets_1/">CPS Representation and Foundational Design Decisions in Flambda2</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//ocamlpro.com/blog/2024_03_19_the_flambda2_snippets_1/">CPS Representation and Foundational Design Decisions in Flambda2</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/monadic-library-for-eio-capabilities/14202">Monadic Library for Eio Capabilities?</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/monadic-library-for-eio-capabilities/14202">Monadic Library for Eio Capabilities?</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/is-there-any-consensus-on-which-type-to-unify-on-for-errors-in-result-types-whats-your-preference/14304">Is there any consensus on which type to unify on for errors in result types? What’s your preference?</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/is-there-any-consensus-on-which-type-to-unify-on-for-errors-in-result-types-whats-your-preference/14304">Is there any consensus on which type to unify on for errors in result types? What’s your preference?</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/create-opam-switch-specifying-custom-c-compiler/14276">Create opam switch specifying custom C compiler</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/create-opam-switch-specifying-custom-c-compiler/14276">Create opam switch specifying custom C compiler</a>.</p> </li> </ul> -<h2 id="视频"><a href="#视频" class="headerlink" title="视频"></a>视频</h2><ul> -<li><p><a href="https://link.zhihu.com/?target=https://watch.ocaml.org/w/b7sv1LQSVZQH6trf4xpwFX">Outreachy Presentations for the December 2023 Round</a>.</p> +<h2 id="视频"><a class="header-anchor" href="#视频">¶</a>视频</h2> +<ul> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//watch.ocaml.org/w/b7sv1LQSVZQH6trf4xpwFX">Outreachy Presentations for the December 2023 Round</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://www.youtube.com/watch?v=IxQ586TS8Gw">Taking Erlang to OCaml 5 (with Leandro Ostera)</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//www.youtube.com/watch%3Fv%3DIxQ586TS8Gw">Taking Erlang to OCaml 5 (with Leandro Ostera)</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://www.youtube.com/watch?v=LwD3GxsY-pc">OCaml Unboxed: An Exploration of Jane Street’s Experiments with OCaml</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//www.youtube.com/watch%3Fv%3DLwD3GxsY-pc">OCaml Unboxed: An Exploration of Jane Street’s Experiments with OCaml</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://www.youtube.com/watch?v=TxuLrsQZprE">OCaml for Fun & Profit: An Experience Report • Tim McGilchrist • YOW! 2023</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//www.youtube.com/watch%3Fv%3DTxuLrsQZprE">OCaml for Fun & Profit: An Experience Report • Tim McGilchrist • YOW! 2023</a>.</p> </li> </ul> -<h2 id="值得注意的项目"><a href="#值得注意的项目" class="headerlink" title="值得注意的项目"></a>值得注意的项目</h2><ul> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ocaml-multicore/eio/releases/tag/v1.0">Eio 1.0: Effects-based direct-style IO for multicore OCaml</a>.</p> +<h2 id="值得注意的项目"><a class="header-anchor" href="#值得注意的项目">¶</a>值得注意的项目</h2> +<ul> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml-multicore/eio/releases/tag/v1.0">Eio 1.0: Effects-based direct-style IO for multicore OCaml</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ocaml-multicore/icfp-2023-eio-tutorial">icfp-2023-eio-tutorial: This tutorial covers how to convert an OCaml 4 program using Lwt for concurrency to use OCaml 5 and Eio.</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml-multicore/icfp-2023-eio-tutorial">icfp-2023-eio-tutorial: This tutorial covers how to convert an OCaml 4 program using Lwt for concurrency to use OCaml 5 and Eio.</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://erratique.ch/software/down">Down: An unintrusive user experience upgrade for the OCaml toplevel system (REPL).</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//erratique.ch/software/down">Down: An unintrusive user experience upgrade for the OCaml toplevel system (REPL).</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/zshipko/ocaml-rs">ocaml-rs: OCaml extensions in Rust</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/zshipko/ocaml-rs">ocaml-rs: OCaml extensions in Rust</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ocaml-multicore/eio-trace">eio-trace: Trace visualisation tool for Eio programs</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml-multicore/eio-trace">eio-trace: Trace visualisation tool for Eio programs</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-dkcoder-0-1-0/14327">[ANN] DkCoder 0.1.0: A transparently installed OCaml 4.14 environment with one API: run a script.</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-dkcoder-0-1-0/14327">[ANN] DkCoder 0.1.0: A transparently installed OCaml 4.14 environment with one API: run a script.</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/darrenldl/docfd/releases/tag/3.0.0">[ANN] Docfd 3.0.0: TUI multiline fuzzy document finder</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/darrenldl/docfd/releases/tag/3.0.0">[ANN] Docfd 3.0.0: TUI multiline fuzzy document finder</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-ocaml-windows-5-1-1/14268">[ANN] Ocaml-windows 5.1.1</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-ocaml-windows-5-1-1/14268">[ANN] Ocaml-windows 5.1.1</a>.</p> </li> -<li><p>这里指的是 <a href="https://link.zhihu.com/?target=https://github.com/ocaml-cross/opam-cross-windows">opam-cross-windows</a> 支持 5.1.1 了,不是 Windows 支持。</p> +<li> +<p>这里指的是 <a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml-cross/opam-cross-windows">opam-cross-windows</a> 支持 5.1.1 了,不是 Windows 支持。</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ml-in-barcelona/quickjs.ml">[ANN] Bindings to QuickJS</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ml-in-barcelona/quickjs.ml">[ANN] Bindings to QuickJS</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/lukstafi/ppx_minidebug">[ANN] ppx_minidebug 1.3.0: toward a logging framework</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/lukstafi/ppx_minidebug">[ANN] ppx_minidebug 1.3.0: toward a logging framework</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/c-cube/ocaml-iostream/releases/tag/v0.2">[ANN] iostream 0.2</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/c-cube/ocaml-iostream/releases/tag/v0.2">[ANN] iostream 0.2</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ocsigen/js_of_ocaml/releases/tag/5.7.1">[ANN] Js_of_ocaml 5.7</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ocsigen/js_of_ocaml/releases/tag/5.7.1">[ANN] Js_of_ocaml 5.7</a>.</p> </li> </ul> -<h2 id="有趣的项目"><a href="#有趣的项目" class="headerlink" title="有趣的项目"></a>有趣的项目</h2><ul> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/pdonadeo/ocaml-lua">ocaml-lua: Lua bindings for OCaml</a>.</p> +<h2 id="有趣的项目"><a class="header-anchor" href="#有趣的项目">¶</a>有趣的项目</h2> +<ul> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/pdonadeo/ocaml-lua">ocaml-lua: Lua bindings for OCaml</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/LexiFi/csml">csml: High-level bindings between .Net and OCaml</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/LexiFi/csml">csml: High-level bindings between .Net and OCaml</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/LexiFi/landmarks">landmarks: A Simple Profiling Library for OCaml</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/LexiFi/landmarks">landmarks: A Simple Profiling Library for OCaml</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://erratique.ch/software/ttweetnacl">Ttweetnacl: An OCaml module providing thin bindings to the TweetNaCl cryptographic library.</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//erratique.ch/software/ttweetnacl">Ttweetnacl: An OCaml module providing thin bindings to the TweetNaCl cryptographic library.</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/xavierleroy/cryptokit">cryptokit: A library of cryptographic primitives (ciphers, hashes, etc) for OCaml</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/xavierleroy/cryptokit">cryptokit: A library of cryptographic primitives (ciphers, hashes, etc) for OCaml</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/gridbugs/llama">llama: A library for building software-defined modular synthesizers in a declarative style.</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/gridbugs/llama">llama: A library for building software-defined modular synthesizers in a declarative style.</a></p> </li> </ul> ]]></content> @@ -1355,58 +1450,70 @@ await prisma.$transaction(async tx => { <entry> <title>OCaml News 2024-5</title> <url>/2024/06/27/OCaml-News-2024-5/</url> - <content><![CDATA[<h2 id="语言的发展"><a href="#语言的发展" class="headerlink" title="语言的发展"></a>语言的发展</h2><ul> -<li><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/pull/13097">Immutable arrays #13097: This PR proposes to add immutable arrays to OCaml.</a></li> -<li><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/pull/13199">Support running native debuggers in ocamltest #13199</a>.</li> -<li><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/pull/13152">The Pattern-Matching Bug: fix totality information by gasche · Pull Request #13152 · ocaml/ocaml</a>.</li> -<li><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/pull/11974%23discussion_r1621832545">Add loongarch architecture support #11974</a>.</li> -<li><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/pull/13101">Add Stdlib.todo #13101</a>.</li> -<li><a href="https://link.zhihu.com/?target=https://tarides.com/blog/2024-06-26-enhancing-the-ocaml-org-community-page-boosting-ux-and-ui-based-on-user-research/">Enhancing the OCaml.org Community Page: Boosting UX and UI Based on User Research.</a></li> -<li><a href="https://link.zhihu.com/?target=https://tarides.com/blog/2024-05-22-launching-the-first-class-windows-project/">Launching the First-Class Windows Project</a>.</li> -</ul> -<h2 id="新消息"><a href="#新消息" class="headerlink" title="新消息"></a>新消息</h2><ul> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-project-wide-occurrences-in-merlin-and-lsp/14847">[ANN] Project wide occurrences in Merlin and LSP</a>.</p> + <content><![CDATA[<h2 id="语言的发展"><a class="header-anchor" href="#语言的发展">¶</a>语言的发展</h2> +<ul> +<li><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/pull/13097">Immutable arrays #13097: This PR proposes to add immutable arrays to OCaml.</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/pull/13199">Support running native debuggers in ocamltest #13199</a>.</li> +<li><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/pull/13152">The Pattern-Matching Bug: fix totality information by gasche · Pull Request #13152 · ocaml/ocaml</a>.</li> +<li><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/pull/11974%23discussion_r1621832545">Add loongarch architecture support #11974</a>.</li> +<li><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/pull/13101">Add Stdlib.todo #13101</a>.</li> +<li><a href="https://link.zhihu.com/?target=https%3A//tarides.com/blog/2024-06-26-enhancing-the-ocaml-org-community-page-boosting-ux-and-ui-based-on-user-research/">Enhancing the OCaml.org Community Page: Boosting UX and UI Based on User Research.</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//tarides.com/blog/2024-05-22-launching-the-first-class-windows-project/">Launching the First-Class Windows Project</a>.</li> +</ul> +<h2 id="新消息"><a class="header-anchor" href="#新消息">¶</a>新消息</h2> +<ul> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-project-wide-occurrences-in-merlin-and-lsp/14847">[ANN] Project wide occurrences in Merlin and LSP</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-opam-2-2-0-rc1-release/14842">[ANN] opam 2.2.0 rc1 release</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-opam-2-2-0-rc1-release/14842">[ANN] opam 2.2.0 rc1 release</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-first-release-of-baby/14840">[ANN] First release of baby</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-first-release-of-baby/14840">[ANN] First release of baby</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/fpottier/baby">baby</a> is an OCaml library that offers several implementations of balanced binary search trees.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/fpottier/baby">baby</a> is an OCaml library that offers several implementations of balanced binary search trees.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-preview-of-stripe-client-and-mock-server-dkstdrestapis/14841">[ANN] Preview of Stripe client and mock server - DkStdRestApis</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-preview-of-stripe-client-and-mock-server-dkstdrestapis/14841">[ANN] Preview of Stripe client and mock server - DkStdRestApis</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-caisar-release-2-0-a-platform-for-characterizing-ai-safety-and-robustness/14831">[ANN] CAISAR release 2.0, a platform for characterizing AI safety and robustness</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-caisar-release-2-0-a-platform-for-characterizing-ai-safety-and-robustness/14831">[ANN] CAISAR release 2.0, a platform for characterizing AI safety and robustness</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-forester-4-1/14800">[ANN] Forester 4.1</a>.</p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-forester-4-1/14800">[ANN] Forester 4.1</a>.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-dream-html-pure-html-3-5-2/14808">[ANN] dream-html & pure-html 3.5.2</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-dream-html-pure-html-3-5-2/14808">[ANN] dream-html & pure-html 3.5.2</a></p> </li> </ul> -<h2 id="有价值的文章"><a href="#有价值的文章" class="headerlink" title="有价值的文章"></a>有价值的文章</h2><ul> -<li><a href="https://link.zhihu.com/?target=https://tarides.com/blog/2024-06-19-keeping-up-with-the-compiler-how-we-help-maintain-the-ocaml-language/">Keeping Up With the Compiler: How we Help Maintain the OCaml Language</a></li> -<li><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/pull/10995">Explain mapping between OCaml memory model and C.</a></li> -<li><a href="https://link.zhihu.com/?target=https://xavierleroy.org/CdF/2023-2024/index.html">Control structures – Xavier Leroy</a>.</li> -<li><a href="https://link.zhihu.com/?target=https://dev.to/chshersh/8-months-of-ocaml-after-8-years-of-haskell-in-production-h96">8 months of OCaml after 8 years of Haskell in production</a>.</li> -<li><a href="https://link.zhihu.com/?target=https://hypirion.com/musings/getting-ocaml-through-the-eye-of-a-needle">Getting OCaml Through the Eye of a Needle</a>.</li> -<li><a href="https://link.zhihu.com/?target=https://tarides.com/blog/2024-06-05-secure-from-the-ground-up-introducing-the-fides-project-combining-risc-v-and-mirageos/">Secure From the Ground Up: Introducing the FIDES Project Combining RISC-V and MirageOS.</a></li> -<li><a href="https://link.zhihu.com/?target=https://tarides.com/blog/2024-05-29-effective-ml-through-merlin-s-destruct-command/">Effective ML Through Merlin’s Destruct Command.</a></li> -<li><a href="https://link.zhihu.com/?target=https://blog.osau.re/articles/reproducible.html">Dinosaure’s website - Reproducibility!</a></li> -<li><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/experiments-in-jitting/14853">Experiments in JITting</a>.</li> -<li><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/how-to-write-an-efficient-cp-r-clone-with-eio/14848">How to write an efficient ‘cp -R’ clone with Eio?</a></li> -<li><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/generating-infix-extension-nodes-with-ppxlib/14833">Generating infix extension nodes with Ppxlib</a>.</li> -<li><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/this-made-my-day-float-to-string-and-string-of-float-without-loss-of-precision/14825">This made my day (float to string and string of float without loss of precision)</a>.</li> -<li><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/help-with-cryptic-dependency-cycle-compile-errors-using-dune-build/14864">Help with cryptic dependency cycle compile errors using <code>dune build</code></a>.</li> -<li><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/why-does-relaxed-value-restriction-treat-function-types-differently/14802">Why does relaxed value restriction treat function types differently?</a></li> -<li><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/binding-existentials-in-a-non-uniform-gadt/14809">Binding existentials in a non-uniform GADT</a>.</li> -</ul> -<h2 id="有趣的项目"><a href="#有趣的项目" class="headerlink" title="有趣的项目"></a>有趣的项目</h2><ul> -<li><a href="https://link.zhihu.com/?target=https://ocaml.org/p/ocaml-index/latest">ocaml-index 1.0 (latest) · OCaml Package: A tool that indexes value usages from cmt files</a>.</li> -<li><a href="https://link.zhihu.com/?target=https://ocaml.org/p/fileutils/latest">fileutils 0.6.4 (latest) · OCaml Package: API to manipulate files (POSIX like) and filenames.</a></li> -<li><a href="https://link.zhihu.com/?target=https://ocaml.org/p/pure-html/latest">pure-html 3.5.2 (latest) · OCaml Package</a></li> -<li><a href="https://link.zhihu.com/?target=https://github.com/fpottier/baby">GitHub - fpottier/baby: A balanced binary search tree library for OCaml</a>.</li> -<li><a href="https://link.zhihu.com/?target=https://github.com/akabe/ocaml-jupyter">GitHub - akabe/ocaml-jupyter: An OCaml kernel for Jupyter (IPython) notebook</a>.</li> -<li><a href="https://link.zhihu.com/?target=https://github.com/robur-coop/orb">Github - robur-coop/orb: check opam package reproductibility.</a></li> -<li><a href="https://link.zhihu.com/?target=https://github.com/ocaml-multicore/dscheck%23motivation">Github - ocaml-multicore/dscheck: Experimental model checker for testing concurrent algorithms.</a></li> +<h2 id="有价值的文章"><a class="header-anchor" href="#有价值的文章">¶</a>有价值的文章</h2> +<ul> +<li><a href="https://link.zhihu.com/?target=https%3A//tarides.com/blog/2024-06-19-keeping-up-with-the-compiler-how-we-help-maintain-the-ocaml-language/">Keeping Up With the Compiler: How we Help Maintain the OCaml Language</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/pull/10995">Explain mapping between OCaml memory model and C.</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//xavierleroy.org/CdF/2023-2024/index.html">Control structures – Xavier Leroy</a>.</li> +<li><a href="https://link.zhihu.com/?target=https%3A//dev.to/chshersh/8-months-of-ocaml-after-8-years-of-haskell-in-production-h96">8 months of OCaml after 8 years of Haskell in production</a>.</li> +<li><a href="https://link.zhihu.com/?target=https%3A//hypirion.com/musings/getting-ocaml-through-the-eye-of-a-needle">Getting OCaml Through the Eye of a Needle</a>.</li> +<li><a href="https://link.zhihu.com/?target=https%3A//tarides.com/blog/2024-06-05-secure-from-the-ground-up-introducing-the-fides-project-combining-risc-v-and-mirageos/">Secure From the Ground Up: Introducing the FIDES Project Combining RISC-V and MirageOS.</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//tarides.com/blog/2024-05-29-effective-ml-through-merlin-s-destruct-command/">Effective ML Through Merlin’s Destruct Command.</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//blog.osau.re/articles/reproducible.html">Dinosaure’s website - Reproducibility!</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/experiments-in-jitting/14853">Experiments in JITting</a>.</li> +<li><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/how-to-write-an-efficient-cp-r-clone-with-eio/14848">How to write an efficient ‘cp -R’ clone with Eio?</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/generating-infix-extension-nodes-with-ppxlib/14833">Generating infix extension nodes with Ppxlib</a>.</li> +<li><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/this-made-my-day-float-to-string-and-string-of-float-without-loss-of-precision/14825">This made my day (float to string and string of float without loss of precision)</a>.</li> +<li><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/help-with-cryptic-dependency-cycle-compile-errors-using-dune-build/14864">Help with cryptic dependency cycle compile errors using <code>dune build</code></a>.</li> +<li><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/why-does-relaxed-value-restriction-treat-function-types-differently/14802">Why does relaxed value restriction treat function types differently?</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/binding-existentials-in-a-non-uniform-gadt/14809">Binding existentials in a non-uniform GADT</a>.</li> +</ul> +<h2 id="有趣的项目"><a class="header-anchor" href="#有趣的项目">¶</a>有趣的项目</h2> +<ul> +<li><a href="https://link.zhihu.com/?target=https%3A//ocaml.org/p/ocaml-index/latest">ocaml-index 1.0 (latest) · OCaml Package: A tool that indexes value usages from cmt files</a>.</li> +<li><a href="https://link.zhihu.com/?target=https%3A//ocaml.org/p/fileutils/latest">fileutils 0.6.4 (latest) · OCaml Package: API to manipulate files (POSIX like) and filenames.</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//ocaml.org/p/pure-html/latest">pure-html 3.5.2 (latest) · OCaml Package</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//github.com/fpottier/baby">GitHub - fpottier/baby: A balanced binary search tree library for OCaml</a>.</li> +<li><a href="https://link.zhihu.com/?target=https%3A//github.com/akabe/ocaml-jupyter">GitHub - akabe/ocaml-jupyter: An OCaml kernel for Jupyter (IPython) notebook</a>.</li> +<li><a href="https://link.zhihu.com/?target=https%3A//github.com/robur-coop/orb">Github - robur-coop/orb: check opam package reproductibility.</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml-multicore/dscheck%23motivation">Github - ocaml-multicore/dscheck: Experimental model checker for testing concurrent algorithms.</a></li> </ul> ]]></content> <tags> @@ -1417,91 +1524,133 @@ await prisma.$transaction(async tx => { <title>OCaml News 2024-6</title> <url>/2024/07/23/OCaml-News-2024-6/</url> <content><![CDATA[<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line"> ^o3</span><br><span class="line">~/\_/\_|)</span><br><span class="line">|/=_=\|</span><br><span class="line">" "</span><br></pre></td></tr></table></figure> - -<h2 id="语言的发展"><a href="#语言的发展" class="headerlink" title="语言的发展"></a>语言的发展</h2><ul> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/pull/13275">Modular explicits #13275</a></p> +<h2 id="语言的发展"><a class="header-anchor" href="#语言的发展">¶</a>语言的发展</h2> +<ul> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/pull/13275">Modular explicits #13275</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/pull/12828">Add short syntax for dependent functor types #12828</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/pull/12828">Add short syntax for dependent functor types #12828</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/pull/13310">Add Pair module to standard library #13310</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/pull/13310">Add Pair module to standard library #13310</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/pull/13272">Allow maximum number of domains to be specified as a OCAMLRUNPARAM parameter #13272</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/pull/13272">Allow maximum number of domains to be specified as a OCAMLRUNPARAM parameter #13272</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/pull/13097">Immutable arrays #13097</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/pull/13097">Immutable arrays #13097</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/pull/13161">Restore native armv7 support for NetBSD 10.0 #13161</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/pull/13161">Restore native armv7 support for NetBSD 10.0 #13161</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/pull/12309">Add effect syntax #12309</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/pull/12309">Add effect syntax #12309</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/pull/12114">Add ThreadSanitizer support #12114</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/pull/12114">Add ThreadSanitizer support #12114</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/pull/13195">A new abstract data type of enumerations in Set.Make(Ord).Enum #13195</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/pull/13195">A new abstract data type of enumerations in Set.Make(Ord).Enum #13195</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/pull/12871">Stdlib priority queues #12871</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/pull/12871">Stdlib priority queues #12871</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/pull/9080">Aliasing == and != with explicit names #9080</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/pull/9080">Aliasing == and != with explicit names #9080</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/pull/12964">Memory cleanup at exit #12964</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/pull/12964">Memory cleanup at exit #12964</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/pull/13169">A document type for error messages #13169</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/pull/13169">A document type for error messages #13169</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/pull/13318">Fix GC alarm regression #13318</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/pull/13318">Fix GC alarm regression #13318</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/pull/13326">Implement O_APPEND on windows #13326</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/pull/13326">Implement O_APPEND on windows #13326</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/pull/13296">Add missing functions from Array to Dynarray #13296</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/pull/13296">Add missing functions from Array to Dynarray #13296</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/pull/12182%23discussion_r1678134261">Improve the type clash error message #12182</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/pull/12182%23discussion_r1678134261">Improve the type clash error message #12182</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/pull/12298">Emphasize that Bigarray.int refers to the OCaml int type, and not the C int type #12298</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/pull/12298">Emphasize that Bigarray.int refers to the OCaml int type, and not the C int type #12298</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/effects-with-lwt-a-dead-end-for-now/15002">Effects with Lwt, a dead end for now?</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/effects-with-lwt-a-dead-end-for-now/15002">Effects with Lwt, a dead end for now?</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/changes-in-handling-of-gc-parameters-and-alarms-in-5-2-0/14986">Changes in handling of Gc parameters and alarms in 5.2.0</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/changes-in-handling-of-gc-parameters-and-alarms-in-5-2-0/14986">Changes in handling of Gc parameters and alarms in 5.2.0</a></p> </li> </ul> -<h2 id="新消息"><a href="#新消息" class="headerlink" title="新消息"></a>新消息</h2><ul> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-mopsa-1-0-modular-open-platform-for-static-analysis/15013">[ANN] Mopsa 1.0 – Modular Open Platform for Static Analysis</a></p> +<h2 id="新消息"><a class="header-anchor" href="#新消息">¶</a>新消息</h2> +<ul> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-mopsa-1-0-modular-open-platform-for-static-analysis/15013">[ANN] Mopsa 1.0 – Modular Open Platform for Static Analysis</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-a-small-extension-of-bigarray-genarray-adding-iteration-mapping-and-folding/15005">[ANN] A small extension of Bigarray.Genarray adding iteration, mapping and folding</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-a-small-extension-of-bigarray-genarray-adding-iteration-mapping-and-folding/15005">[ANN] A small extension of Bigarray.Genarray adding iteration, mapping and folding</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-cudajit-bindings-to-the-cuda-and-nvrtc-libraries/15010">[ANN] cudajit: Bindings to the <code>cuda</code> and <code>nvrtc</code> libraries</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-cudajit-bindings-to-the-cuda-and-nvrtc-libraries/15010">[ANN] cudajit: Bindings to the <code>cuda</code> and <code>nvrtc</code> libraries</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-ocaml-lsp-1-18-0/14952">[ANN] OCaml LSP 1.18.0</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-ocaml-lsp-1-18-0/14952">[ANN] OCaml LSP 1.18.0</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-ortac-0-3-0-dynamic-formal-verification-made-easy/14936">[ANN] Ortac 0.3.0 Dynamic formal verification made easy</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-ortac-0-3-0-dynamic-formal-verification-made-easy/14936">[ANN] Ortac 0.3.0 Dynamic formal verification made easy</a></p> </li> </ul> -<h2 id="有价值的文章"><a href="#有价值的文章" class="headerlink" title="有价值的文章"></a>有价值的文章</h2><ul> -<li><p><a href="https://link.zhihu.com/?target=https://hal.sorbonne-universite.fr/hal-02890500v1/document">Combinations of Reusable Abstract Domains for a Multilingual Static Analyzer</a></p> +<h2 id="有价值的文章"><a class="header-anchor" href="#有价值的文章">¶</a>有价值的文章</h2> +<ul> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//hal.sorbonne-universite.fr/hal-02890500v1/document">Combinations of Reusable Abstract Domains for a Multilingual Static Analyzer</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://fizzixnerd.com/blog/2024-07-21-fixing-living/">Fighting Mutation with Mutation in Living</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//fizzixnerd.com/blog/2024-07-21-fixing-living/">Fighting Mutation with Mutation in Living</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/type-system-and-polymorphic-lets/14990">Type system and polymorphic let’s</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/type-system-and-polymorphic-lets/14990">Type system and polymorphic let’s</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/using-docusaurus-to-document-an-ocaml-project/13359">Using Docusaurus to document an OCaml project</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/using-docusaurus-to-document-an-ocaml-project/13359">Using Docusaurus to document an OCaml project</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/exploring-the-docusaurus-odoc-combo/15012">Exploring the Docusaurus+Odoc combo</a><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/type-system-and-polymorphic-lets/14990">Type system and polymorphic let’s</a><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/exploring-the-docusaurus-odoc-combo/15012">Exploring the Docusaurus+Odoc combo</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/exploring-the-docusaurus-odoc-combo/15012">Exploring the Docusaurus+Odoc combo</a><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/type-system-and-polymorphic-lets/14990">Type system and polymorphic let’s</a><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/exploring-the-docusaurus-odoc-combo/15012">Exploring the Docusaurus+Odoc combo</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://fizzixnerd.com/blog/2024-07-11-a-possibly-safer-interface-to-the-ctypes-ffi/">A (Possibly) Safer Interface to the Ctypes FFI</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//fizzixnerd.com/blog/2024-07-11-a-possibly-safer-interface-to-the-ctypes-ffi/">A (Possibly) Safer Interface to the Ctypes FFI</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://fizzixnerd.com/blog/2024-07-09-ocaml-ffi-sharp-edges-and-how-to-avoid-them/">OCaml FFI Sharp Edges – and How to Avoid them!</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//fizzixnerd.com/blog/2024-07-09-ocaml-ffi-sharp-edges-and-how-to-avoid-them/">OCaml FFI Sharp Edges – and How to Avoid them!</a></p> </li> </ul> -<h2 id="有趣的项目"><a href="#有趣的项目" class="headerlink" title="有趣的项目"></a>有趣的项目</h2><ul> -<li><p><a href="https://link.zhihu.com/?target=https://ocaml.libvirt.org/">ocaml-libvirt OCaml bindings for libvirt</a></p> +<h2 id="有趣的项目"><a class="header-anchor" href="#有趣的项目">¶</a>有趣的项目</h2> +<ul> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//ocaml.libvirt.org/">ocaml-libvirt OCaml bindings for libvirt</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://gitlab.com/mopsa/mopsa-analyzer/">Gitlab - MOPSA/MOPSA analyzer: stands for Modular and Open Platform for Static Analysis.</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//gitlab.com/mopsa/mopsa-analyzer/">Gitlab - MOPSA/MOPSA analyzer: stands for Modular and Open Platform for Static Analysis.</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/Heyji2/GenArrayIter">GitHub - Heyji2/GenArrayIter: Adding iteration, mapping and folding to the ocaml BigArray.Genarrays module which provides arrays of arbitrary dimensions</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/Heyji2/GenArrayIter">GitHub - Heyji2/GenArrayIter: Adding iteration, mapping and folding to the ocaml BigArray.Genarrays module which provides arrays of arbitrary dimensions</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/mbarbin/bopkit">GitHub - mbarbin/bopkit: An educational project for digital circuits programming</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/mbarbin/bopkit">GitHub - mbarbin/bopkit: An educational project for digital circuits programming</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/dx3mod/rpmfile">GitHub - dx3mod/rpmfile: A library for reading metadata from RPM packages.</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/dx3mod/rpmfile">GitHub - dx3mod/rpmfile: A library for reading metadata from RPM packages.</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/gildor478/ocaml-fileutils">Github - gildor478/ocaml-fileutils: OCaml API to manipulate real files (POSIX like) and filenames</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/gildor478/ocaml-fileutils">Github - gildor478/ocaml-fileutils: OCaml API to manipulate real files (POSIX like) and filenames</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/NathanReb/ocaml-api-watch">Github - NathanReb/ocaml-api-watch: Libraries and tools to keep watch on you OCaml lib’s API changes</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/NathanReb/ocaml-api-watch">Github - NathanReb/ocaml-api-watch: Libraries and tools to keep watch on you OCaml lib’s API changes</a></p> </li> </ul> ]]></content> @@ -1513,143 +1662,198 @@ await prisma.$transaction(async tx => { <title>OCaml News 2024-7</title> <url>/2024/12/15/OCaml-News-2024-7/</url> <content><![CDATA[<figure class="highlight text"><table><tr><td class="code"><pre><span class="line"> ^o3</span><br><span class="line">~/\_/\_|)</span><br><span class="line">|/=_=\|</span><br><span class="line">" "</span><br><span class="line"></span><br><span class="line">^~~~~~~~~~~~这其实是用 ASCII 画的一个骆驼。</span><br></pre></td></tr></table></figure> - -<h3 id="语言的发展"><a href="#语言的发展" class="headerlink" title="语言的发展"></a>语言的发展</h3><ul> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ocaml-5-2-1-released/15634">OCaml 5.2.1 released</a></p> +<h3 id="语言的发展"><a class="header-anchor" href="#语言的发展">¶</a>语言的发展</h3> +<ul> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ocaml-5-2-1-released/15634">OCaml 5.2.1 released</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/feedback-help-wanted-upcoming-ocaml-org-cookbook-feature/14127">Feedback / Help Wanted: Upcoming OCaml.org Cookbook Feature</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/feedback-help-wanted-upcoming-ocaml-org-cookbook-feature/14127">Feedback / Help Wanted: Upcoming OCaml.org Cookbook Feature</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/second-beta-release-of-ocaml-5-3-0/15700">Second beta release of OCaml 5.3.0</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/second-beta-release-of-ocaml-5-3-0/15700">Second beta release of OCaml 5.3.0</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/terrateams-open-source-ocaml-repository/15645">Terrateam’s open source Ocaml repository</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/terrateams-open-source-ocaml-repository/15645">Terrateam’s open source Ocaml repository</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-mlx-syntax-dialect/15035">[ANN] .mlx syntax dialect</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-mlx-syntax-dialect/15035">[ANN] .mlx syntax dialect</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-opam-2-3-0-is-out/15609">[ANN] opam 2.3.0 is out!</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-opam-2-3-0-is-out/15609">[ANN] opam 2.3.0 is out!</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://fun-ocaml.com/">Fun OCaml 2024 - Berlin - September 16+17, 2024</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//fun-ocaml.com/">Fun OCaml 2024 - Berlin - September 16+17, 2024</a></p> </li> -<li><p><strong><a href="https://link.zhihu.com/?target=https://www.youtube.com/@FUNOCaml">Fun OCaml is an open source hacking event dedicated to OCaml enthusiasts and professionals around the globe!</a></strong></p> +<li> +<p><strong><a href="https://link.zhihu.com/?target=https%3A//www.youtube.com/%40FUNOCaml">Fun OCaml is an open source hacking event dedicated to OCaml enthusiasts and professionals around the globe!</a></strong></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/pull/13526">Simplify the build of cross compilers by shym · Pull Request #13526 · ocaml/ocaml</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/pull/13526">Simplify the build of cross compilers by shym · Pull Request #13526 · ocaml/ocaml</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/pull/13580">“Mark-delay” performance improvement to major GC by NickBarnes · Pull Request #13580 · ocaml/ocaml</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/pull/13580">“Mark-delay” performance improvement to major GC by NickBarnes · Pull Request #13580 · ocaml/ocaml</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/pull/13416">Use WinAPI concurrency primitives on Windows ports (remove winpthreads) by MisterDA · Pull Request #13416 · ocaml/ocaml</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/pull/13416">Use WinAPI concurrency primitives on Windows ports (remove winpthreads) by MisterDA · Pull Request #13416 · ocaml/ocaml</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://github.com/ocaml/ocaml/pull/13404">Atomic record fields by clef-men · Pull Request #13404 · ocaml/ocaml</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml/ocaml/pull/13404">Atomic record fields by clef-men · Pull Request #13404 · ocaml/ocaml</a></p> </li> </ul> -<h3 id="视频"><a href="#视频" class="headerlink" title="视频"></a>视频</h3><ul> -<li><a href="https://link.zhihu.com/?target=https://www.youtube.com/playlist?list=PLP3MfTGqcNVJMFcWWDF6VSPJB7zuKN5yQ">All the talk recordings from FUN OCaml 2024 in Berlin, September 16 + 17, 2024.</a></li> -<li><a href="https://link.zhihu.com/?target=https://www.youtube.com/watch?v=wbrELQrzwQk">[ICFP24] Oxidizing OCaml with Modal Memory Management</a></li> -<li><a href="https://link.zhihu.com/?target=https://www.youtube.com/watch?v=7yYC6EGYg10">[OCaml24] Priodomainslib: Prioritized Fine-grained Parallelism for Multicore OCaml</a></li> -<li><a href="https://link.zhihu.com/?target=https://www.youtube.com/watch?v=KEkmcXVtFi0">[OCaml24] ChorCaml: Functional Choreographic Programming in OCaml</a></li> -<li><a href="https://link.zhihu.com/?target=https://www.youtube.com/watch?v=vanyv3ZEto8">[OCaml24] Saturn: a library of verified concurrent data structures for OCaml 5</a></li> -<li><a href="https://link.zhihu.com/?target=https://www.youtube.com/watch?v=mUzOBC3V0ds">Beyond the Basics of LSP: Advanced IDE services for OCaml</a></li> -<li><a href="https://link.zhihu.com/?target=https://www.youtube.com/watch?v=BUpRPSzkrH0">Why Terrateam chose OCaml</a></li> -<li><a href="https://link.zhihu.com/?target=https://www.youtube.com/watch?v=8zTN3rtcED4">A Crash Course in OCaml Modules • Tim McGilchrist • YOW! 2015</a></li> -<li><a href="https://link.zhihu.com/?target=https://watch.ocaml.org/w/peT3MdWjS1BYYMbowEJ1gv">Outreachy May 2024 Demo</a></li> -<li><a href="https://link.zhihu.com/?target=https://www.youtube.com/watch?v=JFZvnGD_hV8">Octane: A Query Builder for OCaml</a></li> -</ul> -<h3 id="讨论"><a href="#讨论" class="headerlink" title="讨论"></a>讨论</h3><ul> -<li><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/what-are-the-biggest-reasons-newcomers-give-up-on-ocaml/10958">What are the biggest reasons newcomers give up on OCaml?</a></li> -<li><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/do-you-use-return-to-describe-a-function/15615">Do you use “return” to describe a function?</a></li> -<li><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ocaml-cycle-detection-and-garbage-collector/15757">OCaml Cycle detection and Garbage Collector</a></li> -<li><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/modeling-rust-trait-objects-subtyping-relation-via-ocaml-polymorphic-variants/15644">Modeling Rust trait objects subtyping relation via OCaml polymorphic variants</a></li> -<li><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ocamldebug-using-dune/15595">Ocamldebug using dune</a></li> -<li><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/typesafe-sql-with-octane-ml/15582">Typesafe SQL with Octane.ml</a></li> -</ul> -<h3 id="文章"><a href="#文章" class="headerlink" title="文章"></a>文章</h3><ul> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/using-map-and-ppx-yojson/12524">Using Map and ppx yojson</a></p> +<h3 id="视频"><a class="header-anchor" href="#视频">¶</a>视频</h3> +<ul> +<li><a href="https://link.zhihu.com/?target=https%3A//www.youtube.com/playlist%3Flist%3DPLP3MfTGqcNVJMFcWWDF6VSPJB7zuKN5yQ">All the talk recordings from FUN OCaml 2024 in Berlin, September 16 + 17, 2024.</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//www.youtube.com/watch%3Fv%3DwbrELQrzwQk">[ICFP24] Oxidizing OCaml with Modal Memory Management</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//www.youtube.com/watch%3Fv%3D7yYC6EGYg10">[OCaml24] Priodomainslib: Prioritized Fine-grained Parallelism for Multicore OCaml</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//www.youtube.com/watch%3Fv%3DKEkmcXVtFi0">[OCaml24] ChorCaml: Functional Choreographic Programming in OCaml</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//www.youtube.com/watch%3Fv%3Dvanyv3ZEto8">[OCaml24] Saturn: a library of verified concurrent data structures for OCaml 5</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//www.youtube.com/watch%3Fv%3DmUzOBC3V0ds">Beyond the Basics of LSP: Advanced IDE services for OCaml</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//www.youtube.com/watch%3Fv%3DBUpRPSzkrH0">Why Terrateam chose OCaml</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//www.youtube.com/watch%3Fv%3D8zTN3rtcED4">A Crash Course in OCaml Modules • Tim McGilchrist • YOW! 2015</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//watch.ocaml.org/w/peT3MdWjS1BYYMbowEJ1gv">Outreachy May 2024 Demo</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//www.youtube.com/watch%3Fv%3DJFZvnGD_hV8">Octane: A Query Builder for OCaml</a></li> +</ul> +<h3 id="讨论"><a class="header-anchor" href="#讨论">¶</a>讨论</h3> +<ul> +<li><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/what-are-the-biggest-reasons-newcomers-give-up-on-ocaml/10958">What are the biggest reasons newcomers give up on OCaml?</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/do-you-use-return-to-describe-a-function/15615">Do you use “return” to describe a function?</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ocaml-cycle-detection-and-garbage-collector/15757">OCaml Cycle detection and Garbage Collector</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/modeling-rust-trait-objects-subtyping-relation-via-ocaml-polymorphic-variants/15644">Modeling Rust trait objects subtyping relation via OCaml polymorphic variants</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ocamldebug-using-dune/15595">Ocamldebug using dune</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/typesafe-sql-with-octane-ml/15582">Typesafe SQL with Octane.ml</a></li> +</ul> +<h3 id="文章"><a class="header-anchor" href="#文章">¶</a>文章</h3> +<ul> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/using-map-and-ppx-yojson/12524">Using Map and ppx yojson</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/correct-syntax-to-add-compare-ppx/15764">Correct syntax to add compare ppx</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/correct-syntax-to-add-compare-ppx/15764">Correct syntax to add compare ppx</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/tiny-educational-concurrent-i-o-and-promises-library/15703">Tiny educational concurrent I/O and promises library</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/tiny-educational-concurrent-i-o-and-promises-library/15703">Tiny educational concurrent I/O and promises library</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/good-example-of-handwritten-lexer-recursive-descent-parser/15672">Good example of handwritten Lexer + Recursive Descent Parser?</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/good-example-of-handwritten-lexer-recursive-descent-parser/15672">Good example of handwritten Lexer + Recursive Descent Parser?</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/new-part-pragmatic-category-theory-part-2-published/15056">[NEW PART] Pragmatic Category Theory: Part 2 published!</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/new-part-pragmatic-category-theory-part-2-published/15056">[NEW PART] Pragmatic Category Theory: Part 2 published!</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://dev.to/chshersh/pragmatic-category-theory-part-1-semigroup-intro-1ign">Pragmatic Category Theory | Part 1: Semigroup Intro</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//dev.to/chshersh/pragmatic-category-theory-part-1-semigroup-intro-1ign">Pragmatic Category Theory | Part 1: Semigroup Intro</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://dev.to/chshersh/pragmatic-category-theory-part-2-composing-semigroups-87">Pragmatic Category Theory | Part 2: Composing Semigroups</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//dev.to/chshersh/pragmatic-category-theory-part-2-composing-semigroups-87">Pragmatic Category Theory | Part 2: Composing Semigroups</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/installing-ocaml-on-a-mac-m1-mini/15642">Installing OCaml on a mac m1 mini</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/installing-ocaml-on-a-mac-m1-mini/15642">Installing OCaml on a mac m1 mini</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/a-case-for-feminism-in-programming-language-design/15478">« A Case for Feminism in Programming Language Design »</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/a-case-for-feminism-in-programming-language-design/15478">« A Case for Feminism in Programming Language Design »</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://dl.acm.org/doi/pdf/10.1145/3689492.3689809">A Case for Feminism in Programming Language Design.pdf</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//dl.acm.org/doi/pdf/10.1145/3689492.3689809">A Case for Feminism in Programming Language Design.pdf</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://www.lexifi.com/blog/ocaml/decoders/">Vdom 0.3 brings Elm-style decoders to OCaml</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//www.lexifi.com/blog/ocaml/decoders/">Vdom 0.3 brings Elm-style decoders to OCaml</a></p> </li> </ul> -<h3 id="生态"><a href="#生态" class="headerlink" title="生态"></a>生态</h3><ul> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/re2ocaml-regexp-compiler/15669">Re2ocaml regexp compiler</a></p> +<h3 id="生态"><a class="header-anchor" href="#生态">¶</a>生态</h3> +<ul> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/re2ocaml-regexp-compiler/15669">Re2ocaml regexp compiler</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/eliom-11-1-towards-web-assembly-support/15704">Eliom 11.1: Towards Web Assembly support</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/eliom-11-1-towards-web-assembly-support/15704">Eliom 11.1: Towards Web Assembly support</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-new-releases-of-merlin-and-ocaml-lsp/15752">[ANN] New releases of Merlin and OCaml-LSP</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-new-releases-of-merlin-and-ocaml-lsp/15752">[ANN] New releases of Merlin and OCaml-LSP</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/new-release-of-baby/15754">New release of baby</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/new-release-of-baby/15754">New release of baby</a></p> </li> -<li><p><code>baby</code>is an OCaml library that offers persistent sets and maps based on balanced binary search trees. It offers replacements for OCaml’s<code>Set</code>and<code>Map</code>modules.</p> +<li> +<p><code>baby</code>is an OCaml library that offers persistent sets and maps based on balanced binary search trees. It offers replacements for OCaml’s<code>Set</code>and<code>Map</code>modules.</p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-dune-3-17/15770">[ANN] Dune 3.17</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-dune-3-17/15770">[ANN] Dune 3.17</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-jsont-0-1-0-declarative-json-data-manipulation-for-ocaml/15702">[ANN] Jsont 0.1.0 – Declarative JSON data manipulation for OCaml</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-jsont-0-1-0-declarative-json-data-manipulation-for-ocaml/15702">[ANN] Jsont 0.1.0 – Declarative JSON data manipulation for OCaml</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-release-of-saturn-1-0/15763">[ANN] Release of Saturn 1.0</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-release-of-saturn-1-0/15763">[ANN] Release of Saturn 1.0</a></p> <ul> <li>Saturn is a collection of concurrent-safe data structures designed for OCaml 5.</li> </ul> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-areas-and-adversaries/15706/3">[ANN] Areas and Adversaries</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-areas-and-adversaries/15706/3">[ANN] Areas and Adversaries</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-release-of-cppo-1-8-0/15749">[ANN] Release of cppo 1.8.0</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-release-of-cppo-1-8-0/15749">[ANN] Release of cppo 1.8.0</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-capnp-rpc-2-0/15739">[ANN] capnp-rpc 2.0</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-capnp-rpc-2-0/15739">[ANN] capnp-rpc 2.0</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-advent-of-code-project-template/13539">[ANN] Advent of Code project template</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-advent-of-code-project-template/13539">[ANN] Advent of Code project template</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-testo-0-1-0-a-new-testing-framework-for-ocaml/15624">[ANN] Testo 0.1.0 - a new testing framework for OCaml</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-testo-0-1-0-a-new-testing-framework-for-ocaml/15624">[ANN] Testo 0.1.0 - a new testing framework for OCaml</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-vdom-0-3-functional-ui-applications-now-with-custom-event-handlers/13298">[ANN] vdom 0.3: functional UI applications now with custom event handlers</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-vdom-0-3-functional-ui-applications-now-with-custom-event-handlers/13298">[ANN] vdom 0.3: functional UI applications now with custom event handlers</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/visualizing-dependencies-between-ocaml-modules/15254">Visualizing dependencies between Ocaml modules</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/visualizing-dependencies-between-ocaml-modules/15254">Visualizing dependencies between Ocaml modules</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-mariadb-1-2-0/15709">[ANN] mariadb 1.2.0</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-mariadb-1-2-0/15709">[ANN] mariadb 1.2.0</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-new-release-of-monolith/15701">[ANN] New release of Monolith</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-new-release-of-monolith/15701">[ANN] New release of Monolith</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-first-release-of-hachis/15309">[ANN] First release of hachis</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-first-release-of-hachis/15309">[ANN] First release of hachis</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-liquidsoap-2-3-0/15677">[ANN] Liquidsoap 2.3.0</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-liquidsoap-2-3-0/15677">[ANN] Liquidsoap 2.3.0</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-dream-html-pure-html-3-5-2/14808/3">[ANN] dream-html & pure-html 3.5.2</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-dream-html-pure-html-3-5-2/14808/3">[ANN] dream-html & pure-html 3.5.2</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-js-of-ocaml-5-9-0/15674">[ANN] Js_of_ocaml 5.9.0</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-js-of-ocaml-5-9-0/15674">[ANN] Js_of_ocaml 5.9.0</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-ppx-deriving-ezjsonm/15637">[ANN] ppx_deriving_ezjsonm</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-ppx-deriving-ezjsonm/15637">[ANN] ppx_deriving_ezjsonm</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-smaws-preview-release-an-aws-sdk-for-ocaml-using-eio/15635">[ANN] smaws preview release, an AWS SDK for OCaml using eio</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-smaws-preview-release-an-aws-sdk-for-ocaml-using-eio/15635">[ANN] smaws preview release, an AWS SDK for OCaml using eio</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-aws-s3-4-0-1/2451">[ANN] aws-s3 4.0.1</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-aws-s3-4-0-1/2451">[ANN] aws-s3 4.0.1</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/first-release-of-cmdlang/15616">First release of cmdlang</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/first-release-of-cmdlang/15616">First release of cmdlang</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-eliom-11-and-ocsigen-start-7/15487">[ANN] Eliom 11 and Ocsigen Start 7</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-eliom-11-and-ocsigen-start-7/15487">[ANN] Eliom 11 and Ocsigen Start 7</a></p> </li> -<li><p><a href="https://link.zhihu.com/?target=https://discuss.ocaml.org/t/ann-jane-street-ocaml-extensions-now-with-developer-tooling/15597">[ANN] Jane Street OCaml extensions – now with developer tooling!</a></p> +<li> +<p><a href="https://link.zhihu.com/?target=https%3A//discuss.ocaml.org/t/ann-jane-street-ocaml-extensions-now-with-developer-tooling/15597">[ANN] Jane Street OCaml extensions – now with developer tooling!</a></p> </li> </ul> -<h3 id="亮点项目"><a href="#亮点项目" class="headerlink" title="亮点项目"></a>亮点项目</h3><ul> -<li><a href="https://link.zhihu.com/?target=https://github.com/tjdevries/octane.ml">GitHub - tjdevries/octane.ml: The fastest, hottest</a></li> -<li><a href="https://link.zhihu.com/?target=https://github.com/semgrep/testo">Github - semgrep/testo: Test framework for OCaml</a></li> -<li><a href="https://link.zhihu.com/?target=https://github.com/sim642/odep">GitHub - sim642/odep: Dependency graphs for OCaml modules, libraries and packages</a></li> -<li><a href="https://link.zhihu.com/?target=https://github.com/LexiFi/ocaml-vdom">GitHub - LexiFi/ocaml-vdom: Elm architecture and (V)DOM for OCaml</a></li> -<li><a href="https://link.zhihu.com/?target=https://github.com/ocaml-community/ocaml-mariadb">GitHub - ocaml-community/ocaml-mariadb: OCaml bindings to MariaDB, supporting the nonblocking API</a></li> -<li><a href="https://link.zhihu.com/?target=https://cambium.inria.fr/~fpottier/monolith/doc/monolith/Monolith/">Monolith (monolith.Monolith)</a>: Monolith offers facilities for testing an OCaml library by comparing its implementation (known as the candidate implementation) against a reference implementation.</li> +<h3 id="亮点项目"><a class="header-anchor" href="#亮点项目">¶</a>亮点项目</h3> +<ul> +<li><a href="https://link.zhihu.com/?target=https%3A//github.com/tjdevries/octane.ml">GitHub - tjdevries/octane.ml: The fastest, hottest</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//github.com/semgrep/testo">Github - semgrep/testo: Test framework for OCaml</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//github.com/sim642/odep">GitHub - sim642/odep: Dependency graphs for OCaml modules, libraries and packages</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//github.com/LexiFi/ocaml-vdom">GitHub - LexiFi/ocaml-vdom: Elm architecture and (V)DOM for OCaml</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//github.com/ocaml-community/ocaml-mariadb">GitHub - ocaml-community/ocaml-mariadb: OCaml bindings to MariaDB, supporting the nonblocking API</a></li> +<li><a href="https://link.zhihu.com/?target=https%3A//cambium.inria.fr/~fpottier/monolith/doc/monolith/Monolith/">Monolith (monolith.Monolith)</a>: Monolith offers facilities for testing an OCaml library by comparing its implementation (known as the candidate implementation) against a reference implementation.</li> </ul> ]]></content> <tags> @@ -1661,29 +1865,30 @@ await prisma.$transaction(async tx => { <url>/2024/10/06/Obsidian-Vault-%E7%9A%84-obsidian-%E7%9B%AE%E5%BD%95%E4%B8%AD%E7%9A%84%E5%90%84%E6%96%87%E4%BB%B6%E4%BD%9C%E7%94%A8/</url> <content><![CDATA[<p>一个简单的例子是:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">.obsidian</span><br><span class="line">├── appearance.json</span><br><span class="line">├── app.json</span><br><span class="line">├── community-plugins.json</span><br><span class="line">├── core-plugins.json</span><br><span class="line">├── core-plugins-migration.json</span><br><span class="line">├── plugins</span><br><span class="line">│ └── obsidian-git</span><br><span class="line">│ ├── data.json</span><br><span class="line">│ ├── main.js</span><br><span class="line">│ ├── manifest.json</span><br><span class="line">│ └── styles.css</span><br><span class="line">└── workspace.json</span><br></pre></td></tr></table></figure> - <p>其中:</p> <ul> -<li><p><code>appearance.json</code> 包含当前 vault 的外观设置,例如主题、字体大小和行高,例如:</p> +<li><code>appearance.json</code> 包含当前 vault 的外观设置,例如主题、字体大小和行高,例如:</li> +</ul> <figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"interfaceFontFamily"</span><span class="punctuation">:</span> <span class="string">"HarmonyOS Sans SC"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"textFontFamily"</span><span class="punctuation">:</span> <span class="string">"HarmonyOS Sans SC"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"monospaceFontFamily"</span><span class="punctuation">:</span> <span class="string">"FrankMono"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"accentColor"</span><span class="punctuation">:</span> <span class="string">""</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"cssTheme"</span><span class="punctuation">:</span> <span class="string">"Listive"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"nativeMenus"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">false</span></span></span><br><span class="line"><span class="punctuation">}</span></span><br></pre></td></tr></table></figure> -</li> -<li><p><code>app.json</code> 包含了编辑器的一些设置,例如 vim mode 和断行设置:</p> +<ul> +<li><code>app.json</code> 包含了编辑器的一些设置,例如 vim mode 和断行设置:</li> +</ul> <figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"vimMode"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">true</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"strictLineBreaks"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">false</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"promptDelete"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">false</span></span></span><br><span class="line"><span class="punctuation">}</span></span><br></pre></td></tr></table></figure> -</li> -<li><p><code>community-plugins.json</code>:包含有关当前 vault 中安装的社区插件的数据,例如:</p> +<ul> +<li><code>community-plugins.json</code>:包含有关当前 vault 中安装的社区插件的数据,例如:</li> +</ul> <figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">[</span></span><br><span class="line"> <span class="string">"dataview"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="string">"novel-word-count"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="string">"remotely-save"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="string">"obsidian-tasks-plugin"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="string">"obsidian-style-settings"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="string">"obsidian-advanced-slides"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="string">"calendar"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="string">"3d-graph-new"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="string">"webpage-html-export"</span></span><br><span class="line"><span class="punctuation">]</span></span><br></pre></td></tr></table></figure> -</li> -<li><p><code>core-plugins.json</code>: 就是当前 valut 中的所有内置插件,例如:</p> +<ul> +<li><code>core-plugins.json</code>: 就是当前 valut 中的所有内置插件,例如:</li> +</ul> <figure class="highlight json"><table><tr><td class="code"><pre><span class="line"> <span class="string">"file-explorer"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="string">"global-search"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="string">"switcher"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="string">"graph"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="string">"backlink"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="string">"canvas"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="string">"outgoing-link"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="string">"tag-pane"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="string">"page-preview"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="string">"daily-notes"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="string">"templates"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="string">"note-composer"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="string">"command-palette"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="string">"editor-status"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="string">"bookmarks"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="string">"outline"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="string">"word-count"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="string">"file-recovery"</span></span><br><span class="line"><span class="punctuation">]</span></span><br></pre></td></tr></table></figure> - -<pre><code> - `core-plugins-migration.json`: 就是 `core-plugins.json` 中的内置插件的开关状态,例如: +<pre><code> - `core-plugins-migration.json`: 就是 `core-plugins.json` 中的内置插件的开关状态,例如: </code></pre> -</li> -</ul> <figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"file-explorer"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">true</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"global-search"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">true</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"switcher"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">true</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"graph"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">true</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"backlink"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">true</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"canvas"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">true</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"outgoing-link"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">true</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"tag-pane"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">true</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"properties"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">false</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"page-preview"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">true</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"daily-notes"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">true</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"templates"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">true</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"note-composer"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">true</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"command-palette"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">true</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"slash-command"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">false</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"editor-status"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">true</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"bookmarks"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">true</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"markdown-importer"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">false</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"zk-prefixer"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">false</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"random-note"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">false</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"outline"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">true</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"word-count"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">true</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"slides"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">false</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"audio-recorder"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">false</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"workspaces"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">false</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"file-recovery"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">true</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"publish"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">false</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"sync"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">false</span></span></span><br><span class="line"><span class="punctuation">}</span></span><br></pre></td></tr></table></figure> <ul> -<li><code>workspace.json</code>:包含有关当前 Vault 工作区的数据,包括打开的文件、窗口和布局的设置,例如:<figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"main"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"id"</span><span class="punctuation">:</span> <span class="string">"7bc59326f5497d4a"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"type"</span><span class="punctuation">:</span> <span class="string">"split"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"children"</span><span class="punctuation">:</span> <span class="punctuation">[</span></span><br><span class="line"> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"id"</span><span class="punctuation">:</span> <span class="string">"06fc674d29eb4c3a"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"type"</span><span class="punctuation">:</span> <span class="string">"tabs"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"children"</span><span class="punctuation">:</span> <span class="punctuation">[</span></span><br><span class="line"> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"id"</span><span class="punctuation">:</span> <span class="string">"97d62f14e2fad2f0"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"type"</span><span class="punctuation">:</span> <span class="string">"leaf"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"state"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"type"</span><span class="punctuation">:</span> <span class="string">"markdown"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"state"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"file"</span><span class="punctuation">:</span> <span class="string">"README.md"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"mode"</span><span class="punctuation">:</span> <span class="string">"source"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"source"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">false</span></span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> <span class="punctuation">}</span><span class="punctuation">,</span></span><br><span class="line"> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"id"</span><span class="punctuation">:</span> <span class="string">"c94063b5e5f6f995"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"type"</span><span class="punctuation">:</span> <span class="string">"leaf"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"state"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"type"</span><span class="punctuation">:</span> <span class="string">"markdown"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"state"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"file"</span><span class="punctuation">:</span> <span class="string">"README.md"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"mode"</span><span class="punctuation">:</span> <span class="string">"source"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"source"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">false</span></span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> <span class="punctuation">}</span><span class="punctuation">,</span></span><br><span class="line"> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"id"</span><span class="punctuation">:</span> <span class="string">"143d5ea7a56d7e1d"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"type"</span><span class="punctuation">:</span> <span class="string">"leaf"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"state"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"type"</span><span class="punctuation">:</span> <span class="string">"markdown"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"state"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"file"</span><span class="punctuation">:</span> <span class="string">"测试.md"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"mode"</span><span class="punctuation">:</span> <span class="string">"source"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"source"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">false</span></span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> <span class="punctuation">]</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"currentTab"</span><span class="punctuation">:</span> <span class="number">2</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> ...</span><br></pre></td></tr></table></figure></li> +<li><code>workspace.json</code>:包含有关当前 Vault 工作区的数据,包括打开的文件、窗口和布局的设置,例如:</li> </ul> +<figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"main"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"id"</span><span class="punctuation">:</span> <span class="string">"7bc59326f5497d4a"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"type"</span><span class="punctuation">:</span> <span class="string">"split"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"children"</span><span class="punctuation">:</span> <span class="punctuation">[</span></span><br><span class="line"> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"id"</span><span class="punctuation">:</span> <span class="string">"06fc674d29eb4c3a"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"type"</span><span class="punctuation">:</span> <span class="string">"tabs"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"children"</span><span class="punctuation">:</span> <span class="punctuation">[</span></span><br><span class="line"> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"id"</span><span class="punctuation">:</span> <span class="string">"97d62f14e2fad2f0"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"type"</span><span class="punctuation">:</span> <span class="string">"leaf"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"state"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"type"</span><span class="punctuation">:</span> <span class="string">"markdown"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"state"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"file"</span><span class="punctuation">:</span> <span class="string">"README.md"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"mode"</span><span class="punctuation">:</span> <span class="string">"source"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"source"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">false</span></span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> <span class="punctuation">}</span><span class="punctuation">,</span></span><br><span class="line"> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"id"</span><span class="punctuation">:</span> <span class="string">"c94063b5e5f6f995"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"type"</span><span class="punctuation">:</span> <span class="string">"leaf"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"state"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"type"</span><span class="punctuation">:</span> <span class="string">"markdown"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"state"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"file"</span><span class="punctuation">:</span> <span class="string">"README.md"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"mode"</span><span class="punctuation">:</span> <span class="string">"source"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"source"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">false</span></span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> <span class="punctuation">}</span><span class="punctuation">,</span></span><br><span class="line"> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"id"</span><span class="punctuation">:</span> <span class="string">"143d5ea7a56d7e1d"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"type"</span><span class="punctuation">:</span> <span class="string">"leaf"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"state"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"type"</span><span class="punctuation">:</span> <span class="string">"markdown"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"state"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"file"</span><span class="punctuation">:</span> <span class="string">"测试.md"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"mode"</span><span class="punctuation">:</span> <span class="string">"source"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"source"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">false</span></span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> <span class="punctuation">]</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"currentTab"</span><span class="punctuation">:</span> <span class="number">2</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> ...</span><br></pre></td></tr></table></figure> ]]></content> <tags> <tag>Technique</tag> @@ -1695,8 +1900,8 @@ await prisma.$transaction(async tx => { <content><![CDATA[<blockquote> <p>A relation field can also reference its own model, in this case the relation is called a <em>self-relation</em>. Self-relations can be of any cardinality, 1-1, 1-n and m-n.</p> </blockquote> -<h2 id="一对一"><a href="#一对一" class="headerlink" title="一对一"></a>一对一</h2><figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">model User {</span><br><span class="line"> id Int @id @default(autoincrement())</span><br><span class="line"> name String?</span><br><span class="line"> successorId Int? @unique</span><br><span class="line"> successor User? @relation("BlogOwnerHistory", fields: [successorId], references: [id])</span><br><span class="line"> predecessor User? @relation("BlogOwnerHistory")</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - +<h2 id="一对一"><a class="header-anchor" href="#一对一">¶</a>一对一</h2> +<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">model User {</span><br><span class="line"> id Int @id @default(autoincrement())</span><br><span class="line"> name String?</span><br><span class="line"> successorId Int? @unique</span><br><span class="line"> successor User? @relation("BlogOwnerHistory", fields: [successorId], references: [id])</span><br><span class="line"> predecessor User? @relation("BlogOwnerHistory")</span><br><span class="line">}</span><br></pre></td></tr></table></figure> <p>User 展现了这样一个模型:</p> <ul> <li>User 可以有一个或零个前驱(predecessor)</li> @@ -1714,9 +1919,8 @@ await prisma.$transaction(async tx => { </blockquote> <p>而在关系型数据库中,一对一的 self-relation 可以用如下 SQL 描述:</p> <figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">CREATE TABLE</span> "User" (</span><br><span class="line"> id SERIAL <span class="keyword">PRIMARY KEY</span>,</span><br><span class="line"> "name" TEXT,</span><br><span class="line"> "successorId" <span class="type">INTEGER</span></span><br><span class="line">);</span><br><span class="line"></span><br><span class="line"><span class="keyword">ALTER TABLE</span> "User" <span class="keyword">ADD CONSTRAINT</span> fk_successor_user <span class="keyword">FOREIGN KEY</span> ("successorId") <span class="keyword">REFERENCES</span> "User" (id);</span><br><span class="line"></span><br><span class="line"><span class="keyword">ALTER TABLE</span> "User" <span class="keyword">ADD CONSTRAINT</span> successor_unique <span class="keyword">UNIQUE</span> ("successorId");</span><br></pre></td></tr></table></figure> - -<h2 id="一对多"><a href="#一对多" class="headerlink" title="一对多"></a>一对多</h2><figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">model User {</span><br><span class="line"> id Int @id @default(autoincrement())</span><br><span class="line"> name String?</span><br><span class="line"> teacherId Int?</span><br><span class="line"> teacher User? @relation("TeacherStudents", fields: [teacherId], references: [id])</span><br><span class="line"> students User[] @relation("TeacherStudents")</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - +<h2 id="一对多"><a class="header-anchor" href="#一对多">¶</a>一对多</h2> +<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">model User {</span><br><span class="line"> id Int @id @default(autoincrement())</span><br><span class="line"> name String?</span><br><span class="line"> teacherId Int?</span><br><span class="line"> teacher User? @relation("TeacherStudents", fields: [teacherId], references: [id])</span><br><span class="line"> students User[] @relation("TeacherStudents")</span><br><span class="line">}</span><br></pre></td></tr></table></figure> <p>User 展现了这样一个模型:</p> <ul> <li>一个 User 只能有零个或一个 teacher</li> @@ -1727,27 +1931,26 @@ await prisma.$transaction(async tx => { </blockquote> <p>用 SQL 描述 User model:</p> <figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">CREATE TABLE</span> "User" (</span><br><span class="line"> id SERIAL <span class="keyword">PRIMARY KEY</span>,</span><br><span class="line"> "name" TEXT,</span><br><span class="line"> "teacherId" <span class="type">INTEGER</span></span><br><span class="line">);</span><br><span class="line"></span><br><span class="line"><span class="keyword">ALTER TABLE</span> "User" <span class="keyword">ADD CONSTRAINT</span> fk_teacherid_user <span class="keyword">FOREIGN KEY</span> ("teacherId") <span class="keyword">REFERENCES</span> "User" (id);</span><br></pre></td></tr></table></figure> - <p><code>teacherId</code> 没有使用 <code>UNIQUE</code> 约束,这代表着多个 students 可以有同一个 teacher</p> -<h2 id="多对多"><a href="#多对多" class="headerlink" title="多对多"></a>多对多</h2><figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">model User {</span><br><span class="line"> id Int @id @default(autoincrement())</span><br><span class="line"> name String?</span><br><span class="line"> followedBy User[] @relation("UserFollows")</span><br><span class="line"> following User[] @relation("UserFollows")</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - +<h2 id="多对多"><a class="header-anchor" href="#多对多">¶</a>多对多</h2> +<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">model User {</span><br><span class="line"> id Int @id @default(autoincrement())</span><br><span class="line"> name String?</span><br><span class="line"> followedBy User[] @relation("UserFollows")</span><br><span class="line"> following User[] @relation("UserFollows")</span><br><span class="line">}</span><br></pre></td></tr></table></figure> <ul> <li>一个 User 可以被零个或多个 Users 关注</li> <li>一个 User 可以关注零个或多个 Users</li> </ul> <blockquote> -<p>对于关系型数据库,多对多的关系是隐式的,这意味着 Prisma ORM 会在底层数据库中维护一个 <a href="https://www.prisma.io/docs/orm/prisma-schema/data-model/relations/many-to-many-relations#relation-tables">relation table</a>:<br>A relation table (also sometimes called a <em>JOIN</em>, <em>link</em> or <em>pivot</em> table) connects two or more other tables and therefore creates a <em>relation</em> between them. Creating relation tables is a common data modelling practice in SQL to represent relationships between different entities. In essence it means that “one m-n relation is modeled as two 1-n relations in the database”.</p> +<p>对于关系型数据库,多对多的关系是隐式的,这意味着 Prisma ORM 会在底层数据库中维护一个 <a href="https://www.prisma.io/docs/orm/prisma-schema/data-model/relations/many-to-many-relations#relation-tables">relation table</a>:<br> +A relation table (also sometimes called a <em>JOIN</em>, <em>link</em> or <em>pivot</em> table) connects two or more other tables and therefore creates a <em>relation</em> between them. Creating relation tables is a common data modelling practice in SQL to represent relationships between different entities. In essence it means that “one m-n relation is modeled as two 1-n relations in the database”.</p> <p>We recommend using <a href="https://www.prisma.io/docs/orm/prisma-schema/data-model/relations/many-to-many-relations#implicit-many-to-many-relations">implicit</a> m-n-relations, where Prisma ORM automatically generates the relation table in the underlying database. <a href="https://www.prisma.io/docs/orm/prisma-schema/data-model/relations/many-to-many-relations#explicit-many-to-many-relations">Explicit</a> m-n-relations should be used when you need to store additional data in the relations, such as the date the relation was created.</p> </blockquote> <p>如果需要需要通过多对多的关系来保存其他字段,也可以创建<a href="https://www.prisma.io/docs/orm/prisma-schema/data-model/relations/many-to-many-relations#explicit-many-to-many-relations">显式</a>的多对多 self 关系:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">model User {</span><br><span class="line"> id Int @id @default(autoincrement())</span><br><span class="line"> name String?</span><br><span class="line"> followedBy Follows[] @relation("followedBy")</span><br><span class="line"> following Follows[] @relation("following")</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line">model Follows {</span><br><span class="line"> followedBy User @relation("followedBy", fields: [followedById], references: [id])</span><br><span class="line"> followedById Int</span><br><span class="line"> following User @relation("following", fields: [followingId], references: [id])</span><br><span class="line"> followingId Int</span><br><span class="line"></span><br><span class="line"> @@id([followingId, followedById])</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - <p>在关系型数据库中,可以用如下 SQL 描述:</p> <figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">CREATE TABLE</span> "User" (</span><br><span class="line"> id <span class="type">integer</span> <span class="keyword">DEFAULT</span> nextval(<span class="string">'"User_id_seq"'</span>::regclass) <span class="keyword">PRIMARY KEY</span>,</span><br><span class="line"> name text</span><br><span class="line">);</span><br><span class="line"><span class="keyword">CREATE TABLE</span> "_UserFollows" (</span><br><span class="line"> "A" <span class="type">integer</span> <span class="keyword">NOT NULL</span> <span class="keyword">REFERENCES</span> "User"(id) <span class="keyword">ON</span> <span class="keyword">DELETE</span> CASCADE <span class="keyword">ON</span> <span class="keyword">UPDATE</span> CASCADE,</span><br><span class="line"> "B" <span class="type">integer</span> <span class="keyword">NOT NULL</span> <span class="keyword">REFERENCES</span> "User"(id) <span class="keyword">ON</span> <span class="keyword">DELETE</span> CASCADE <span class="keyword">ON</span> <span class="keyword">UPDATE</span> CASCADE</span><br><span class="line">);</span><br></pre></td></tr></table></figure> - -<h2 id="在同一模型上建立多个-self-relations"><a href="#在同一模型上建立多个-self-relations" class="headerlink" title="在同一模型上建立多个 self-relations"></a>在同一模型上建立多个 self-relations</h2><figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">model User {</span><br><span class="line"> id Int @id @default(autoincrement())</span><br><span class="line"> name String?</span><br><span class="line"> teacherId Int?</span><br><span class="line"> teacher User? @relation("TeacherStudents", fields: [teacherId], references: [id])</span><br><span class="line"> students User[] @relation("TeacherStudents")</span><br><span class="line"> followedBy User[] @relation("UserFollows")</span><br><span class="line"> following User[] @relation("UserFollows")</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - -<h2 id="REFS"><a href="#REFS" class="headerlink" title="REFS."></a>REFS.</h2><ul> +<h2 id="在同一模型上建立多个-self-relations"><a class="header-anchor" href="#在同一模型上建立多个-self-relations">¶</a>在同一模型上建立多个 self-relations</h2> +<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">model User {</span><br><span class="line"> id Int @id @default(autoincrement())</span><br><span class="line"> name String?</span><br><span class="line"> teacherId Int?</span><br><span class="line"> teacher User? @relation("TeacherStudents", fields: [teacherId], references: [id])</span><br><span class="line"> students User[] @relation("TeacherStudents")</span><br><span class="line"> followedBy User[] @relation("UserFollows")</span><br><span class="line"> following User[] @relation("UserFollows")</span><br><span class="line">}</span><br></pre></td></tr></table></figure> +<h2 id="REFS"><a class="header-anchor" href="#REFS">¶</a>REFS.</h2> +<ul> <li><a href="https://www.prisma.io/docs/orm/prisma-schema/data-model/relations#relation-fields">fully annotated</a></li> <li><a href="https://www.prisma.io/docs/orm/prisma-schema/data-model/models#optional-and-mandatory-fields">required</a></li> <li><a href="https://www.prisma.io/docs/orm/prisma-schema/data-model/relations/many-to-many-relations#implicit-many-to-many-relations">implicit</a></li> @@ -1766,7 +1969,7 @@ await prisma.$transaction(async tx => { <p>Ten years prior to presentation, he underwent surgical decompression for syringomyelia.</p> <p>A magnetic resonance imaging (MRI) scan of his cervical and thoracic spine performed 2 years prior to presentation revealed a recurrent syrinx extending from Cl C1 to T11, which was not resected because it did not cause symptoms at that time.</p> <p>On physical examination, he had mild tenderness to palpation and reduced range of motion of the left shoulder with abduction and flexion limited to 120° (normal range of motion, 180°).</p> -<p>The left scapular muscles were atrophic, and pain and temperature sensation were reduced in his proximal left arm, and dorsal aspect of his left shoulder. </p> +<p>The left scapular muscles were atrophic, and pain and temperature sensation were reduced in his proximal left arm, and dorsal aspect of his left shoulder.</p> <p>His complete blood cell count, serum glucose levels, C-reactive protein levels, and erythrocyte sedimentation rate were normal.</p> <p>Results of tests for rheumatoid factor and antinuclear antibody were negative.</p> <p>Left shoulder radiograph showed complete absence of the left humeral head and a well-demarcated smooth osseous margin of the proximal humerus with associated soft tissue swelling and periarticular calcification.</p> @@ -1774,7 +1977,8 @@ await prisma.$transaction(async tx => { <ul> <li><a href="/papers/Radiographic%20Absence%20of%20the%20Left%20Humeral%20Head.pdf">报告原档</a></li> </ul> -<p>这里提到了一种罕见的进展性疾病, 叫Charcot肩, 是一种神经性关节病变,特点是关节迅速被破坏和相关软组织肿胀。患者通常表现为肩部逐渐增大的肿胀,可能伴有疼痛或无痛,肩部无力和活动范围减少。<br>大约80%的Charcot肩患者有脊髓空洞症, 表现为脊髓中的液体充满腔体</p> +<p>这里提到了一种罕见的进展性疾病, 叫Charcot肩, 是一种神经性关节病变,特点是关节迅速被破坏和相关软组织肿胀。患者通常表现为肩部逐渐增大的肿胀,可能伴有疼痛或无痛,肩部无力和活动范围减少。<br> +大约80%的Charcot肩患者有脊髓空洞症, 表现为脊髓中的液体充满腔体</p> ]]></content> <tags> <tag>Medicine</tag> @@ -1789,30 +1993,28 @@ await prisma.$transaction(async tx => { <p>抽象化数据访问层的主要作用是将应用的业务逻辑与对数据库的数据访问等实现细节进行解耦。DB 框架的更改不应该影响到应用程序的核心服务,并且它们应该对业务逻辑代码透明。</p> <p>业务服务应该只依赖于抽象,而不是实现,数据服务同理。</p> <hr> -<h1 id="Intro"><a href="#Intro" class="headerlink" title="Intro."></a>Intro.</h1><p>例如,此时有一个书籍存储的微服务,并且有一个“添加新书籍”的操作用例,在此用例中可以通过使用 <code>Book</code> 这个 <em>Repository</em> 来添加新书籍,而 <code>Book</code> 具体使用什么数据库,怎么存并不是业务需要关心的事情。</p> -<h2 id="具体实现方式"><a href="#具体实现方式" class="headerlink" title="具体实现方式"></a>具体实现方式</h2><p>假设有以下实体类型定义:</p> +<h1>Intro.</h1> +<p>例如,此时有一个书籍存储的微服务,并且有一个“添加新书籍”的操作用例,在此用例中可以通过使用 <code>Book</code> 这个 <em>Repository</em> 来添加新书籍,而 <code>Book</code> 具体使用什么数据库,怎么存并不是业务需要关心的事情。</p> +<h2 id="具体实现方式"><a class="header-anchor" href="#具体实现方式">¶</a>具体实现方式</h2> +<p>假设有以下实体类型定义:</p> <figure class="highlight typescript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">class</span> <span class="title class_">Author</span> {</span><br><span class="line"> <span class="attr">firstName</span>: <span class="built_in">string</span>;</span><br><span class="line"> <span class="attr">lastName</span>: <span class="built_in">string</span>;</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">class</span> <span class="title class_">Genre</span> {</span><br><span class="line"> <span class="attr">name</span>: <span class="built_in">string</span>;</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">class</span> <span class="title class_">Book</span> {</span><br><span class="line"> <span class="attr">title</span>: <span class="built_in">string</span>;</span><br><span class="line"> <span class="attr">author</span>: <span class="title class_">Author</span>;</span><br><span class="line"> <span class="attr">genre</span>: <span class="title class_">Genre</span>;</span><br><span class="line"> <span class="attr">publishDate</span>: <span class="title class_">Date</span>;</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - -<h3 id="抽象化"><a href="#抽象化" class="headerlink" title="抽象化"></a>抽象化</h3><p>第一步是抽象化出一个通用的 <em>Repository</em> ,其中包含通用的操作:</p> +<h3 id="抽象化"><a class="header-anchor" href="#抽象化">¶</a>抽象化</h3> +<p>第一步是抽象化出一个通用的 <em>Repository</em> ,其中包含通用的操作:</p> <figure class="highlight typescript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">IGenericRepository</span><T> {</span><br><span class="line"> <span class="keyword">abstract</span> <span class="title function_">getAll</span>(): <span class="title class_">Promise</span><T[]>;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">abstract</span> <span class="title function_">get</span>(<span class="attr">id</span>: <span class="built_in">string</span>): <span class="title class_">Promise</span><T>;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">abstract</span> <span class="title function_">create</span>(<span class="attr">item</span>: T): <span class="title class_">Promise</span><T>;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">abstract</span> <span class="title function_">update</span>(<span class="attr">id</span>: <span class="built_in">string</span>, <span class="attr">item</span>: T);</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - <ul> <li>这里具体有那些函数可以根据需要(业务)自己定义。</li> <li>类型参数 <code>T</code> 表示每个实体。</li> </ul> -<p>接着,定义一个数据服务,其中包含使用 <code>IGenericRepositoiry</code> 定义的具体实例对应的 _Repository_:</p> +<p>接着,定义一个数据服务,其中包含使用 <code>IGenericRepositoiry</code> 定义的具体实例对应的 <em>Repository</em>:</p> <figure class="highlight typescript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> { <span class="title class_">Author</span>, <span class="title class_">Book</span>, <span class="title class_">Genre</span> } <span class="keyword">from</span> <span class="string">'../entities'</span>;</span><br><span class="line"><span class="keyword">import</span> { <span class="title class_">IGenericRepository</span> } <span class="keyword">from</span> <span class="string">'./generic-repository.abstract'</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">IDataServices</span> {</span><br><span class="line"> <span class="keyword">abstract</span> <span class="attr">authors</span>: <span class="title class_">IGenericRepository</span><<span class="title class_">Author</span>>;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">abstract</span> <span class="attr">books</span>: <span class="title class_">IGenericRepository</span><<span class="title class_">Book</span>>;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">abstract</span> <span class="attr">genres</span>: <span class="title class_">IGenericRepository</span><<span class="title class_">Genre</span>>;</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - <ul> <li>这里有三个 <em>Repository</em> 分别对应不同的实体。</li> <li><code>IGenericRepository</code> 中定义的函数是每个 <em>Repository</em> 公开的通用存储函数。</li> </ul> <p>以上这些就是对业务中的实体的 <em>Repository</em> 抽象,这样就隔离开了业务和存储逻辑,例如使用 MongoDB,可以实现一个 <code>MongoGenericRepository</code>:</p> <figure class="highlight typescript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> { <span class="title class_">Model</span> } <span class="keyword">from</span> <span class="string">'mongoose'</span>;</span><br><span class="line"><span class="keyword">import</span> { <span class="title class_">IGenericRepository</span> } <span class="keyword">from</span> <span class="string">'../../../core'</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">class</span> <span class="title class_">MongoGenericRepository</span><T> <span class="keyword">implements</span> <span class="title class_">IGenericRepository</span><T> {</span><br><span class="line"> <span class="keyword">private</span> <span class="attr">_repository</span>: <span class="title class_">Model</span><T>;</span><br><span class="line"> <span class="keyword">private</span> <span class="attr">_populateOnFind</span>: <span class="built_in">string</span>[];</span><br><span class="line"></span><br><span class="line"> <span class="title function_">constructor</span>(<span class="params"><span class="attr">repository</span>: <span class="title class_">Model</span><T>, <span class="attr">populateOnFind</span>: <span class="built_in">string</span>[] = []</span>) {</span><br><span class="line"> <span class="variable language_">this</span>.<span class="property">_repository</span> = repository;</span><br><span class="line"> <span class="variable language_">this</span>.<span class="property">_populateOnFind</span> = populateOnFind;</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="title function_">getAll</span>(): <span class="title class_">Promise</span><T[]> {</span><br><span class="line"> <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="property">_repository</span>.<span class="title function_">find</span>().<span class="title function_">populate</span>(<span class="variable language_">this</span>.<span class="property">_populateOnFind</span>).<span class="title function_">exec</span>();</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="title function_">get</span>(<span class="attr">id</span>: <span class="built_in">any</span>): <span class="title class_">Promise</span><T> {</span><br><span class="line"> <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="property">_repository</span>.<span class="title function_">findById</span>(id).<span class="title function_">populate</span>(<span class="variable language_">this</span>.<span class="property">_populateOnFind</span>).<span class="title function_">exec</span>();</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="title function_">create</span>(<span class="attr">item</span>: T): <span class="title class_">Promise</span><T> {</span><br><span class="line"> <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="property">_repository</span>.<span class="title function_">create</span>(item);</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="title function_">update</span>(<span class="params"><span class="attr">id</span>: <span class="built_in">string</span>, <span class="attr">item</span>: T</span>) {</span><br><span class="line"> <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="property">_repository</span>.<span class="title function_">findByIdAndUpdate</span>(id, item);</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - <p>然后实现一个 <code>MongoDataServices</code>:</p> <figure class="highlight typescript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> { <span class="title class_">Injectable</span>, <span class="title class_">OnApplicationBootstrap</span> } <span class="keyword">from</span> <span class="string">'@nestjs/common'</span>;</span><br><span class="line"><span class="keyword">import</span> { <span class="title class_">InjectModel</span> } <span class="keyword">from</span> <span class="string">'@nestjs/mongoose'</span>;</span><br><span class="line"><span class="keyword">import</span> { <span class="title class_">Model</span> } <span class="keyword">from</span> <span class="string">'mongoose'</span>;</span><br><span class="line"><span class="keyword">import</span> { <span class="title class_">IDataServices</span> } <span class="keyword">from</span> <span class="string">'../../../core'</span>;</span><br><span class="line"><span class="keyword">import</span> { <span class="title class_">MongoGenericRepository</span> } <span class="keyword">from</span> <span class="string">'./mongo-generic-repository'</span>;</span><br><span class="line"><span class="keyword">import</span> {</span><br><span class="line"> <span class="title class_">Author</span>,</span><br><span class="line"> <span class="title class_">AuthorDocument</span>,</span><br><span class="line"> <span class="title class_">Book</span>,</span><br><span class="line"> <span class="title class_">BookDocument</span>,</span><br><span class="line"> <span class="title class_">Genre</span>,</span><br><span class="line"> <span class="title class_">GenreDocument</span>,</span><br><span class="line">} <span class="keyword">from</span> <span class="string">'./model'</span>;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Injectable</span>()</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">class</span> <span class="title class_">MongoDataServices</span></span><br><span class="line"> <span class="keyword">implements</span> <span class="title class_">IDataServices</span>, <span class="title class_">OnApplicationBootstrap</span></span><br><span class="line">{</span><br><span class="line"> <span class="attr">authors</span>: <span class="title class_">MongoGenericRepository</span><<span class="title class_">Author</span>>;</span><br><span class="line"> <span class="attr">books</span>: <span class="title class_">MongoGenericRepository</span><<span class="title class_">Book</span>>;</span><br><span class="line"> <span class="attr">genres</span>: <span class="title class_">MongoGenericRepository</span><<span class="title class_">Genre</span>>;</span><br><span class="line"></span><br><span class="line"> <span class="title function_">constructor</span>(<span class="params"></span></span><br><span class="line"><span class="params"> <span class="meta">@InjectModel</span>(Author.name)</span></span><br><span class="line"><span class="params"> <span class="keyword">private</span> <span class="title class_">AuthorRepository</span>: <span class="title class_">Model</span><<span class="title class_">AuthorDocument</span>>,</span></span><br><span class="line"><span class="params"> <span class="meta">@InjectModel</span>(Book.name)</span></span><br><span class="line"><span class="params"> <span class="keyword">private</span> <span class="title class_">BookRepository</span>: <span class="title class_">Model</span><<span class="title class_">BookDocument</span>>,</span></span><br><span class="line"><span class="params"> <span class="meta">@InjectModel</span>(Genre.name)</span></span><br><span class="line"><span class="params"> <span class="keyword">private</span> <span class="title class_">GenreRepository</span>: <span class="title class_">Model</span><<span class="title class_">GenreDocument</span>>,</span></span><br><span class="line"><span class="params"> </span>) {}</span><br><span class="line"></span><br><span class="line"> <span class="title function_">onApplicationBootstrap</span>(<span class="params"></span>) {</span><br><span class="line"> <span class="variable language_">this</span>.<span class="property">authors</span> = <span class="keyword">new</span> <span class="title class_">MongoGenericRepository</span><<span class="title class_">Author</span>>(<span class="variable language_">this</span>.<span class="property">AuthorRepository</span>);</span><br><span class="line"> <span class="variable language_">this</span>.<span class="property">books</span> = <span class="keyword">new</span> <span class="title class_">MongoGenericRepository</span><<span class="title class_">Book</span>>(<span class="variable language_">this</span>.<span class="property">BookRepository</span>, [</span><br><span class="line"> <span class="string">'author'</span>,</span><br><span class="line"> <span class="string">'genre'</span>,</span><br><span class="line"> ]);</span><br><span class="line"> <span class="variable language_">this</span>.<span class="property">genres</span> = <span class="keyword">new</span> <span class="title class_">MongoGenericRepository</span><<span class="title class_">Genre</span>>(<span class="variable language_">this</span>.<span class="property">GenreRepository</span>);</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - <hr> <p>Sunday, March 30, 2025 7:58 PM:</p> <p>感觉以上全错,不应该过度抽象 Repository 的,就让它分散在各个模块中,还可以参考 <a href="https://github.com/Papooch/nestjs-cls">https://github.com/Papooch/nestjs-cls</a> 实现不会抽象泄漏的事务性 Repository 方法。</p> @@ -1826,7 +2028,7 @@ await prisma.$transaction(async tx => { <url>/2024/01/22/Rescript-React-Native/</url> <content><![CDATA[<p>Rescript 对 React Native 的支持还算可以,但如今的 RN 已经是 Expo 的 RN 了,所以仍然有些落后,在这个 template 中,我测试了 rescript + rescript-react-native + expo + nativewind 的组合,可以跑起来:</p> <ul> -<li><a href="https://github.com/muqiuhan/rescript-react-native-expo-nativewind-template">muqiuhan/rescript-react-native-expo-nativewind-template</a></li> +<li><a href="https://github.com/muqiuhan/rescript-react-native-expo-nativewind-template">muqiuhan/rescript-react-native-expo-nativewind-template</a></li> </ul> <p>其中有两个问题,一是 <a href="https://github.com/rescript-bindings/expo">rescript-expo</a> 对 rescript v11 的兼容性,我通过简单的注释让其通过编译:</p> <ul> @@ -1834,13 +2036,10 @@ await prisma.$transaction(async tx => { </ul> <p>二是对于 nativewind 的支持,编写的 binding 非常丑陋:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">type default_style = {</span><br><span class="line"> className?: string,</span><br><span class="line"> children?: React.element,</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line">@module("nativewind")</span><br><span class="line">external styled: React.component<'a> => React.component<default_style> = "styled"</span><br><span class="line"></span><br><span class="line">module StyledText = {</span><br><span class="line"> let make = styled(ReactNative.Text.make)</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line">module StyledView = {</span><br><span class="line"> let make = styled(ReactNative.View.make)</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line">module StyledImage = {</span><br><span class="line"> type props = {</span><br><span class="line"> source?: string,</span><br><span class="line"> ...default_style,</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> @module("nativewind")</span><br><span class="line"> external styled: React.component<'a> => React.component<props> = "styled"</span><br><span class="line"></span><br><span class="line"> let make: React.component<props> = styled(ReactNative.Image.make)</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - <p>而这似乎并没有好的解决方案,理想中的实现应该是:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">module Styled = (Component: {</span><br><span class="line"> type params // or type params = 'a</span><br><span class="line"> let make: React.component<props></span><br><span class="line">}) => {</span><br><span class="line"> type props = {</span><br><span class="line"> ...Component.props, // This can't work as it is not defined as record</span><br><span class="line"> className?: string</span><br><span class="line"> }</span><br><span class="line"> @module("nativewind")</span><br><span class="line"> external styled: React.component<Component.props> => React.component<props> = "styled"</span><br><span class="line"></span><br><span class="line"> let make: React.component<props> = styled(Component.make)</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - <p>或者退一步:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">type styledProps = {</span><br><span class="line"> className?: string,</span><br><span class="line"> // ...</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line">@module("nativewind")</span><br><span class="line"> external styled: React.component<'a> => React.component<'b> = "styled"</span><br><span class="line"></span><br><span class="line">module StyledText = {</span><br><span class="line"> type props = {</span><br><span class="line"> ...ReactNative.Text.props,</span><br><span class="line"> ...styledProps</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> let make: React.component<props> = styled(ReactNative.Text.make)</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - <p>但这在当前的 rescript 中,根本无法实现。</p> <p>详细的讨论看这个帖子:</p> <ul> @@ -1856,20 +2055,19 @@ await prisma.$transaction(async tx => { <url>/2024/05/20/Rescript-genType-import-%E9%97%AE%E9%A2%98/</url> <content><![CDATA[<p>Rescript 11 之后,<code>@genType</code> 被合并进编译器,无需任何依赖就能使用,当在 Rescript 中 <code>@genType</code> 了使用某些 Rescript built-in 的基本类型时,可能会生成有问题的 <code>import</code> 相关代码,例如:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">@genType</span><br><span class="line">module LoginResponse = {</span><br><span class="line"> let status = response => {</span><br><span class="line"> response</span><br><span class="line"> ->Js.Json.decodeObject</span><br><span class="line"> ->Option.flatMap(response => {</span><br><span class="line"> response->Js_dict.get("status")</span><br><span class="line"> })</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - <p><code>status</code> 函数具有 <code>Js.Json.t => option<Js.Json.t></code> 类型,那么在生成的 TypeScript 文件中,会出现这样的 import:</p> <figure class="highlight typescript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="keyword">type</span> { <span class="title class_">Json</span>_t <span class="keyword">as</span> <span class="title class_">Js</span>_Json_t } <span class="keyword">from</span> <span class="string">"./Js.gen.tsx"</span></span><br></pre></td></tr></table></figure> - <p>而 <code>Js.gen.tsx</code> 这个文件是不存在的,解决方案是使用 <code>@genType</code> 的 <code>shim</code>:</p> <ul> -<li><p>在 <code>rescript.json</code> 中的 <code>gentypeconfig</code> 中添加 <code>shim</code> 配置:</p> +<li>在 <code>rescript.json</code> 中的 <code>gentypeconfig</code> 中添加 <code>shim</code> 配置:</li> +</ul> <figure class="highlight json"><table><tr><td class="code"><pre><span class="line">...</span><br><span class="line"><span class="attr">"gentypeconfig"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line">...</span><br><span class="line"> <span class="attr">"shims"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"Js"</span><span class="punctuation">:</span> <span class="string">"Js"</span></span><br><span class="line"> <span class="punctuation">}</span><span class="punctuation">,</span></span><br><span class="line">...</span><br><span class="line"><span class="punctuation">}</span></span><br><span class="line">...</span><br></pre></td></tr></table></figure> -</li> -<li><p>然后新建 <code>Js.shim.ts</code>:</p> +<ul> +<li>然后新建 <code>Js.shim.ts</code>:</li> +</ul> <figure class="highlight typescript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">type</span> <span class="title class_">Json</span>_t = <span class="built_in">unknown</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">type</span> t = <span class="built_in">unknown</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">type</span> <span class="title class_">Exn</span>_t = <span class="title class_">Error</span>;</span><br></pre></td></tr></table></figure> -</li> -<li><p>删除原来由 <code>@genType</code> 生成的 TypeScript 文件并重新生成</p> -</li> +<ul> +<li>删除原来由 <code>@genType</code> 生成的 TypeScript 文件并重新生成</li> </ul> <p>现在生成的 TypeScript 文件将会从 <code>Js.shim.ts</code> import 类型:</p> <figure class="highlight typescript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="keyword">type</span> {<span class="title class_">Json</span>_t <span class="keyword">as</span> <span class="title class_">Js</span>_Json_t} <span class="keyword">from</span> <span class="string">'../../src/model/Js.shim.ts'</span>;</span><br></pre></td></tr></table></figure> @@ -1882,14 +2080,15 @@ await prisma.$transaction(async tx => { <title>Rust NewType 模式</title> <url>/2023/05/03/Rust-NewType-%E6%A8%A1%E5%BC%8F/</url> <content><![CDATA[<p>New Type模式是一种软件设计模式,用于在已有类型的基础上创建一个新的类型。在Rust中,这通常是通过定义一个结构体,其中只包含一个单一成员。这个结构体(New Type)对外提供了一个新的、独立的类型,用于对原始类型增加额外的语义或限制。</p> -<h2 id="加强类型安全"><a href="#加强类型安全" class="headerlink" title="加强类型安全"></a>加强类型安全</h2><figure class="highlight rust"><table><tr><td class="code"><pre><span class="line"><span class="keyword">struct</span> <span class="title class_">Meters</span>(<span class="type">f64</span>);</span><br><span class="line"><span class="keyword">struct</span> <span class="title class_">Feet</span>(<span class="type">f64</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> <span class="variable">length_in_meters</span> = <span class="title function_ invoke__">Meters</span>(<span class="number">100.0</span>);</span><br><span class="line"><span class="keyword">let</span> <span class="variable">length_in_feet</span> = <span class="title function_ invoke__">Feet</span>(<span class="number">328.084</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 编译器会防止以下代码执行,因为类型不匹配</span></span><br><span class="line"><span class="comment">// let wrong_length = Meters(length_in_feet); // 编译错误</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 正确的构造</span></span><br><span class="line"><span class="keyword">fn</span> <span class="title function_">add_lengths</span>(length1: Meters, length2: Meters) <span class="punctuation">-></span> Meters {</span><br><span class="line"> <span class="title function_ invoke__">Meters</span>(length1.<span class="number">0</span> + length2.<span class="number">0</span>)</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - +<h2 id="加强类型安全"><a class="header-anchor" href="#加强类型安全">¶</a>加强类型安全</h2> +<figure class="highlight rust"><table><tr><td class="code"><pre><span class="line"><span class="keyword">struct</span> <span class="title class_">Meters</span>(<span class="type">f64</span>);</span><br><span class="line"><span class="keyword">struct</span> <span class="title class_">Feet</span>(<span class="type">f64</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> <span class="variable">length_in_meters</span> = <span class="title function_ invoke__">Meters</span>(<span class="number">100.0</span>);</span><br><span class="line"><span class="keyword">let</span> <span class="variable">length_in_feet</span> = <span class="title function_ invoke__">Feet</span>(<span class="number">328.084</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 编译器会防止以下代码执行,因为类型不匹配</span></span><br><span class="line"><span class="comment">// let wrong_length = Meters(length_in_feet); // 编译错误</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 正确的构造</span></span><br><span class="line"><span class="keyword">fn</span> <span class="title function_">add_lengths</span>(length1: Meters, length2: Meters) <span class="punctuation">-></span> Meters {</span><br><span class="line"> <span class="title function_ invoke__">Meters</span>(length1.<span class="number">0</span> + length2.<span class="number">0</span>)</span><br><span class="line">}</span><br></pre></td></tr></table></figure> <p>这个例子使用 newtype 模式避免将原始类型f64用于不同的量度,从而增强了类型的安全性。</p> -<h2 id="实现特定-trait"><a href="#实现特定-trait" class="headerlink" title="实现特定 trait"></a>实现特定 trait</h2><figure class="highlight rust"><table><tr><td class="code"><pre><span class="line"><span class="keyword">struct</span> <span class="title class_">Kilometers</span>(<span class="type">f64</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">impl</span> <span class="title class_">Kilometers</span> {</span><br><span class="line"> <span class="keyword">fn</span> <span class="title function_">to_miles</span>(&<span class="keyword">self</span>) <span class="punctuation">-></span> <span class="type">f64</span> {</span><br><span class="line"> <span class="keyword">self</span>.<span class="number">0</span> * <span class="number">0.621371</span></span><br><span class="line"> }</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> <span class="variable">distance</span> = <span class="title function_ invoke__">Kilometers</span>(<span class="number">10.0</span>);</span><br><span class="line"><span class="built_in">println!</span>(<span class="string">"The distance in miles is {}"</span>, distance.<span class="title function_ invoke__">to_miles</span>());</span><br></pre></td></tr></table></figure> - +<h2 id="实现特定-trait"><a class="header-anchor" href="#实现特定-trait">¶</a>实现特定 trait</h2> +<figure class="highlight rust"><table><tr><td class="code"><pre><span class="line"><span class="keyword">struct</span> <span class="title class_">Kilometers</span>(<span class="type">f64</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">impl</span> <span class="title class_">Kilometers</span> {</span><br><span class="line"> <span class="keyword">fn</span> <span class="title function_">to_miles</span>(&<span class="keyword">self</span>) <span class="punctuation">-></span> <span class="type">f64</span> {</span><br><span class="line"> <span class="keyword">self</span>.<span class="number">0</span> * <span class="number">0.621371</span></span><br><span class="line"> }</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> <span class="variable">distance</span> = <span class="title function_ invoke__">Kilometers</span>(<span class="number">10.0</span>);</span><br><span class="line"><span class="built_in">println!</span>(<span class="string">"The distance in miles is {}"</span>, distance.<span class="title function_ invoke__">to_miles</span>());</span><br></pre></td></tr></table></figure> <p>这里,Kilometers有一个方法to_miles,该方法是不会影响其他f64数据的。如果我们有另一个表示温度的f64类型,就不会意外调用到与距离相关的方法。</p> <p>New Type模式同样适用于对<code>Box<dyn SomeTrait></code>类型的包装,这可以在需要动态分派(动态调用实现了某个接口的不同类型的对象的方法)的时候提供便利。通过创建一个New Type来包装这样的<code>Box<dyn SomeTrait></code>类型,可以提供自定义的方法或实现更多的trait,同时也可以让API更加清晰和易于使用。</p> -<h2 id="零成本抽象"><a href="#零成本抽象" class="headerlink" title="零成本抽象"></a>零成本抽象</h2><p>在Rust中,New Type模式不仅是类型安全的,还是一种零成本抽象。这是因为Rust编译器在编译时期会进行足够的优化,以确保New Type的使用没有运行时开销。 Rust的零成本抽象原则确保了抽象不会引入额外的运行时成本。例如,当你使用Meters这样的New Type时,Rust确保:</p> +<h2 id="零成本抽象"><a class="header-anchor" href="#零成本抽象">¶</a>零成本抽象</h2> +<p>在Rust中,New Type模式不仅是类型安全的,还是一种零成本抽象。这是因为Rust编译器在编译时期会进行足够的优化,以确保New Type的使用没有运行时开销。 Rust的零成本抽象原则确保了抽象不会引入额外的运行时成本。例如,当你使用Meters这样的New Type时,Rust确保:</p> <ol> <li>无额外内存开销:Meters只包含一个f64,在内存中的表现和单独的f64是一样的。</li> <li>无额外运行时开销:使用Meters时,性能和直接使用f64完全相同。编译器会移除任何关于New Type的包装和解包的代码。</li> @@ -1905,15 +2104,16 @@ await prisma.$transaction(async tx => { <content><![CDATA[<blockquote> <p>在Rust中,PartialEq和PartialOrd trait处理了不是所有值都可以相互比较的情况。</p> </blockquote> -<h2 id="PartialEq-Trait"><a href="#PartialEq-Trait" class="headerlink" title="PartialEq Trait"></a>PartialEq Trait</h2><p>PartialEq trait用于定义值相等性的比较。它的设计允许类型的值之间进行相等(<code>==</code>)和不等(<code>!=</code>)的比较。与其对应的 Eq trait 确保一个类型的所有值都是可以可靠比较的,即满足等价关系的特性,如自反性、对称性和传递性。</p> +<h2 id="PartialEq-Trait"><a class="header-anchor" href="#PartialEq-Trait">¶</a>PartialEq Trait</h2> +<p>PartialEq trait用于定义值相等性的比较。它的设计允许类型的值之间进行相等(<code>==</code>)和不等(<code>!=</code>)的比较。与其对应的 Eq trait 确保一个类型的所有值都是可以可靠比较的,即满足等价关系的特性,如自反性、对称性和传递性。</p> <figure class="highlight rust"><table><tr><td class="code"><pre><span class="line"><span class="keyword">fn</span> <span class="title function_">eq</span>(&<span class="keyword">self</span>, other: &<span class="keyword">Self</span>) <span class="punctuation">-></span> <span class="type">bool</span>;</span><br><span class="line"><span class="keyword">fn</span> <span class="title function_">ne</span>(&<span class="keyword">self</span>, other: &<span class="keyword">Self</span>) <span class="punctuation">-></span> <span class="type">bool</span>;</span><br></pre></td></tr></table></figure> - <p>在大多数情况下,类型的值都能够完全比较相等性,这时可以实现Eq。然而,对于一些特殊类型的值,如浮点数,由于存在无穷大的正负值和NaN值,导致它们的比较更加复杂。例如,根据IEEE浮点数的标准,NaN与任何值(包括它自己)比较都不相等。</p> -<h2 id="PartialOrd-Trait"><a href="#PartialOrd-Trait" class="headerlink" title="PartialOrd Trait"></a>PartialOrd Trait</h2><p>PartialOrd trait用于定义值之间的大小比较。类似于PartialEq,它允许部分比较大小,返回一个Option,表示比较结果可能存在,也可能不存在(即比较无法进行时返回None):</p> +<h2 id="PartialOrd-Trait"><a class="header-anchor" href="#PartialOrd-Trait">¶</a>PartialOrd Trait</h2> +<p>PartialOrd trait用于定义值之间的大小比较。类似于PartialEq,它允许部分比较大小,返回一个Option,表示比较结果可能存在,也可能不存在(即比较无法进行时返回None):</p> <figure class="highlight rust"><table><tr><td class="code"><pre><span class="line"><span class="keyword">fn</span> <span class="title function_">partial_cmp</span>(&<span class="keyword">self</span>, other: &<span class="keyword">Self</span>) <span class="punctuation">-></span> <span class="type">Option</span><Ordering>;</span><br></pre></td></tr></table></figure> - <p>在全部比较可能的场景,我们会使用Ord trait,它要求实现cmp方法,总是返回一个Ordering,表示两个值之间的确切比较关系。Ord是在所有值都能够比较时使用的,例如整数和字符串。</p> -<h2 id="设计用意和解决的问题"><a href="#设计用意和解决的问题" class="headerlink" title="设计用意和解决的问题"></a>设计用意和解决的问题</h2><p>Rust 设计 PartialEq 和 PartialOrd trait 主要出于以下几个理由:</p> +<h2 id="设计用意和解决的问题"><a class="header-anchor" href="#设计用意和解决的问题">¶</a>设计用意和解决的问题</h2> +<p>Rust 设计 PartialEq 和 PartialOrd trait 主要出于以下几个理由:</p> <ul> <li>非总序理念:并不是所有类型都有一个全局的排序方法。例如,复数之间就没有一个自然的大小顺序。为了避免为这些类型人为地赋予一个排序方法,Rust 提供了一个只需部分实现序列操作的选择。</li> <li>IEEE 浮点数标准:由于浮点数标准定义了特殊值(NaN, 正负无穷),以及NaN不等于自身的规则,浮点数在一些情况下不能进行相等性或大小比较。</li> @@ -1933,39 +2133,38 @@ await prisma.$transaction(async tx => { <blockquote> <p>注意:Rust 虚表及其结构属于 Rust 语言的内部实现细节,不保证稳定性。本文所介绍的虚表布局仅反映本文创作时最新的 Rust 虚表结构[1],在将来 Rust 虚表结构可能会发生变化。一个 Rust 程序的正确性不应该以任何方式依赖于 Rust 虚表的结构。</p> </blockquote> -<h2 id="基本结构"><a href="#基本结构" class="headerlink" title="基本结构"></a>基本结构</h2><p>Rust 程序中的所有虚表均以一个固定结构的 header 开头。Header 中按顺序包含三个usize 大小的字段:drop_in_place ,size 和 align 。在 header 之后是一系列的 usize 大小字段,其数量以及含义在每个虚表中可能都不同。</p> +<h2 id="基本结构"><a class="header-anchor" href="#基本结构">¶</a>基本结构</h2> +<p>Rust 程序中的所有虚表均以一个固定结构的 header 开头。Header 中按顺序包含三个usize 大小的字段:drop_in_place ,size 和 align 。在 header 之后是一系列的 usize 大小字段,其数量以及含义在每个虚表中可能都不同。</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">+---------------+</span><br><span class="line">| drop_in_place |</span><br><span class="line">+---------------+</span><br><span class="line">| size |</span><br><span class="line">+---------------+</span><br><span class="line">| align |</span><br><span class="line">+---------------+</span><br><span class="line">| entry1 |</span><br><span class="line">+---------------+</span><br><span class="line">| entry2 |</span><br><span class="line">+---------------+</span><br><span class="line">| entry3 |</span><br><span class="line">+---------------+</span><br></pre></td></tr></table></figure> <p>虚表 header 中的drop_in_place 是一个函数指针,其指向的函数能够原地 drop 当前胖指针所引用的对象。size 和 align 两个域分别给出对象的大小和内存对齐,这两个域共同构成一个 std::alloc::Layout 结构,可用于释放当前胖指针所引用的对象所占据的内存。虚表 header 的存在使得 trait object 总是能被销毁和释放。例如当销毁一个 <code>Box<dyn Trait></code> 时,<code>Box::<dyn Trait>::drop</code> 会首先调用虚表中的 drop_in_place 函数原地销毁 Box 所引用的对象,然后再调用 dealloc 函数并传递虚表中的 size 和 align 释放堆空间。</p> <p>在虚表 header 之后是一系列的字段。在最普遍的情况下,每个字段代表一个指向 trait 所定义的函数的指针。例如,对于下列 object safe 的 trait:</p> <figure class="highlight rust"><table><tr><td class="code"><pre><span class="line"><span class="keyword">pub</span> <span class="keyword">trait</span> <span class="title class_">Trait</span> {</span><br><span class="line"> <span class="keyword">fn</span> <span class="title function_">fun1</span>(&<span class="keyword">self</span>);</span><br><span class="line"> <span class="keyword">fn</span> <span class="title function_">fun2</span>(&<span class="keyword">self</span>);</span><br><span class="line"> <span class="keyword">fn</span> <span class="title function_">fun3</span>(&<span class="keyword">self</span>);</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - <p>如果类型T 实现了 Trait,那么为 T 生成的 Trait 虚表的结构为:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">+--------------------------+</span><br><span class="line">| fn drop_in_place(*mut T) |</span><br><span class="line">+--------------------------+</span><br><span class="line">| size of T |</span><br><span class="line">+--------------------------+</span><br><span class="line">| align of T |</span><br><span class="line">+--------------------------+</span><br><span class="line">| fn <T as Trait>::fun1 |</span><br><span class="line">+--------------------------+</span><br><span class="line">| fn <T as Trait>::fun2 |</span><br><span class="line">+--------------------------+</span><br><span class="line">| fn <T as Trait>::fun3 |</span><br><span class="line">+--------------------------+</span><br></pre></td></tr></table></figure> - <p>Trait 中的函数按照声明顺序依次排列在虚表 header 之后。当通过一个指向 T 对象的 &dyn Trait 调用 fun2 函数时,程序会先从虚表的第 5 个域中得到为 T 实现的 Trait::fun2 函数的地址,然后再调用之。</p> -<h2 id="Super-Trait"><a href="#Super-Trait" class="headerlink" title="Super Trait"></a>Super Trait</h2><p>Object safe 的 trait 可以有 super trait。例如:</p> +<h2 id="Super-Trait"><a class="header-anchor" href="#Super-Trait">¶</a>Super Trait</h2> +<p>Object safe 的 trait 可以有 super trait。例如:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">pub trait Grand {</span><br><span class="line"> fn grand_fun1(&self);</span><br><span class="line"> fn grand_fun2(&self);</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line">pub trait Parent : Grand {</span><br><span class="line"> fn parent_fun1(&self);</span><br><span class="line"> fn parent_fun2(&self);</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line">pub trait Trait : Parent {</span><br><span class="line"> fn fun(&self);</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - <p>如果类型T 实现了 Trait,那么此时为 T 生成的 Trait 虚表的结构为:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">+-------------------------------+</span><br><span class="line">| fn drop_in_place(*mut T) |</span><br><span class="line">+-------------------------------+</span><br><span class="line">| size of T |</span><br><span class="line">+-------------------------------+</span><br><span class="line">| align of T |</span><br><span class="line">+-------------------------------+</span><br><span class="line">| fn <T as Grand>::grand_fun1 |</span><br><span class="line">+-------------------------------+</span><br><span class="line">| fn <T as Grand>::grand_fun2 |</span><br><span class="line">+-------------------------------+</span><br><span class="line">| fn <T as Parent>::parent_fun1 |</span><br><span class="line">+-------------------------------+</span><br><span class="line">| fn <T as Parent>::parent_fun2 |</span><br><span class="line">+-------------------------------+</span><br><span class="line">| fn <T as Trait>::fun |</span><br><span class="line">+-------------------------------+</span><br></pre></td></tr></table></figure> - <p>可以看到,此时Trait 以及 Trait 的所有直接或间接父 trait 所定义的所有函数均包含在虚表 header 之后,且顺序为后序(即先排布 Trait 的父 trait 所定义的所有函数,最后再排布 Trait 所定义的所有函数)。这样的排布方式使得在得到 T 类型的 Trait 虚表的同时也同时得到了 T 类型的 Parent 虚表和 Grand 虚表。T 类型的 Grand 虚表恰好由 Trait 虚表的前五个域构成,T 类型的 Parent 虚表恰好由 Trait 虚表的前七项构成。这使得向上转换变得非常简单。</p> <p>所谓向上转换,即 Rust 允许将&dyn Trait 转换为 &dyn Parent 或 &dyn Grand 。在向上转换的过程中,胖指针的对象地址域保持不变,但 metadata 域可能需要进行调整,因为不同的 trait 可能具有不同的虚表地址。但在当前示例中,向上转换不需要调整 metadata 域,因为一个指向 Trait 虚表的指针同时也指向 Parent 虚表和 Grand 虚表。在后文中我们会进一步介绍需要调整 metadata 域的向上转换的情况。</p> <blockquote> <p>注意:目前 stable Rust 暂不支持向上转换。要使用向上转换特性,必须使用 nightly 工具链,并向源文件中添加 #![feature(trait_upcasting)] 特性开关。</p> </blockquote> -<h2 id="多重继承"><a href="#多重继承" class="headerlink" title="多重继承"></a>多重继承</h2><p>Trait 可以有多个 super trait。例如:</p> +<h2 id="多重继承"><a class="header-anchor" href="#多重继承">¶</a>多重继承</h2> +<p>Trait 可以有多个 super trait。例如:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">pub trait Base {</span><br><span class="line"> fn base_fun1(&self);</span><br><span class="line"> fn base_fun2(&self);</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line">pub trait Left : Base {</span><br><span class="line"> fn left_fun1(&self);</span><br><span class="line"> fn left_fun2(&self);</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line">pub trait Right : Base {</span><br><span class="line"> fn right_fun1(&self);</span><br><span class="line"> fn right_fun2(&self);</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line">pub trait Trait : Left + Right {</span><br><span class="line"> fn fun(&self);</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - <p>如果类型T 实现了 Trait,那么此时为 T 生成的 Trait 虚表的结构为:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">+-----------------------------+</span><br><span class="line">| fn drop_in_place(*mut T) |</span><br><span class="line">+-----------------------------+</span><br><span class="line">| size of T |</span><br><span class="line">+-----------------------------+</span><br><span class="line">| align of T |</span><br><span class="line">+-----------------------------+</span><br><span class="line">| fn <T as Base>::base_fun1 |</span><br><span class="line">+-----------------------------+</span><br><span class="line">| fn <T as Base>::base_fun2 |</span><br><span class="line">+-----------------------------+</span><br><span class="line">| fn <T as Left>::left_fun1 |</span><br><span class="line">+-----------------------------+</span><br><span class="line">| fn <T as Left>::left_fun2 |</span><br><span class="line">+-----------------------------+</span><br><span class="line">| fn <T as Right>::right_fun1 |</span><br><span class="line">+-----------------------------+</span><br><span class="line">| fn <T as Right>::right_fun2 |</span><br><span class="line">+-----------------------------+</span><br><span class="line">| ptr to <T as Right>::vtable |</span><br><span class="line">+-----------------------------+</span><br><span class="line">| fn <T as Trait>::fun |</span><br><span class="line">+-----------------------------+</span><br></pre></td></tr></table></figure> - <p>可以看到,此时Trait 及其所有直接或间接父 trait 所定义的所有函数仍然包含在虚表内,因此通过 &dyn Trait 调用的函数仍然可以直接从虚表内得到其实际目标函数的地址。另外,Trait 虚表内仍然包含有效的 Base 虚表和 Left 虚表。因此,将 &dyn Trait 向上转换为 &dyn Left 或 &dyn Base 仍然是极其简单的,不需要调整胖指针的 metadata 域。但是,将 &dyn Trait 向上转换为 &dyn Right 就需要调整 metadata 域了,因为 Trait 虚表内并不包含一个有效的 Right 虚表。这也是 Trait 虚表中 ptr to <code><T as Right>::vtable</code> 域的作用:在执行向上转换时,程序会读取 Trait 虚表的这个域作为得到的 &dyn Right 胖指针的 metadata 。这也是 <em>Rust 向上转换与 C++ 向上转换的一个很大不同:在 C++ 中的向上转换通常并不需要访问虚表(除非需要执行跨虚继承边界的转换),但在 Rust 中向上转换可能需要访问虚表。</em></p> <p>更加一般地,对于一个 object safe 的 traitTr,将其第一个父 trait、第一个父 trait 的第一个父 trait、…… 这一系列直接或间接父 trait 记为这个 trait 的 PrefixTrait 集合。在将 &dyn Tr 向上转换时,如果转换到的目标 trait 包含在 PrefixTrait 集合内,那么这个向上转换是平凡的:不需要调整胖指针的 metadata 域。否则,这个向上转换需要在 Tr 的虚表内读取目标 trait 的虚表指针作为转换结果的 metadata 。在 Tr 的虚表结构中,位于 PrefixTrait 集合中的父 trait 只需要排布他们所定义的函数即可;对于其他父 trait 还需要额外在虚表内排布一个指向其虚表的指针用于向上转换。</p> -<h2 id="向下转换"><a href="#向下转换" class="headerlink" title="向下转换"></a>向下转换</h2><p>Rust 提供了一个特殊的 trait:std::any::Any 。该 trait 支持向下转换,即可以将 &dyn Any 转换为 T 。转换过程中会对胖指针所指向的对象的实际类型进行检查,确认其确实是一个 T 类型的对象。Any trait 的虚表结构有一些特殊;在虚表 header 之后,Any 虚表仅包含一个域,这个域直接给出胖指针指向的对象的类型标识(由一个 std::any::TypeId 类型的值表示)。例如,对于任意的 T: ‘static,编译器为其生成的 Any 虚表为:</p> +<h2 id="向下转换"><a class="header-anchor" href="#向下转换">¶</a>向下转换</h2> +<p>Rust 提供了一个特殊的 trait:std::any::Any 。该 trait 支持向下转换,即可以将 &dyn Any 转换为 T 。转换过程中会对胖指针所指向的对象的实际类型进行检查,确认其确实是一个 T 类型的对象。Any trait 的虚表结构有一些特殊;在虚表 header 之后,Any 虚表仅包含一个域,这个域直接给出胖指针指向的对象的类型标识(由一个 std::any::TypeId 类型的值表示)。例如,对于任意的 T: 'static,编译器为其生成的 Any 虚表为:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">+--------------------------+</span><br><span class="line">| fn drop_in_place(*mut T) |</span><br><span class="line">+--------------------------+</span><br><span class="line">| size of T |</span><br><span class="line">+--------------------------+</span><br><span class="line">| align of T |</span><br><span class="line">+--------------------------+</span><br><span class="line">| TypeId of T |</span><br><span class="line">+--------------------------+</span><br></pre></td></tr></table></figure> <p>在执行向下转换时,程序首先检查转换到的类型是否与虚表中给出的TypeId 所标识的类型一致。若类型检查通过,向下转换操作可以直接返回胖指针中的指针域作为转换结果。</p> -<h3 id="REFERENCE"><a href="#REFERENCE" class="headerlink" title="REFERENCE"></a>REFERENCE</h3><ol> +<h3 id="REFERENCE"><a class="header-anchor" href="#REFERENCE">¶</a>REFERENCE</h3> +<ol> <li>Vtable format to support dyn upcasting coercion <a href="https://rust-lang.github.io/dyn-upcasting-coercion-initiative/design-discussions/vtable-layout.*html">https://rust-lang.github.io/dyn-upcasting-coercion-initiative/design-discussions/vtable-layout.*html</a>*</li> </ol> ]]></content> @@ -1978,13 +2177,12 @@ await prisma.$transaction(async tx => { <url>/2023/05/24/Rust-%E9%97%AD%E5%8C%85-lifetime-may-not-live-long-enough-%E9%97%AE%E9%A2%98/</url> <content><![CDATA[<p>代码:</p> <figure class="highlight rust"><table><tr><td class="code"><pre><span class="line">...</span><br><span class="line"> <span class="keyword">fn</span> <span class="title function_">handlers</span>(<span class="keyword">self</span>) <span class="punctuation">-></span> crate::server::request::Handlers {</span><br><span class="line"> <span class="built_in">vec!</span>[(</span><br><span class="line"> <span class="string">"/tree"</span>,</span><br><span class="line"> routing::<span class="title function_ invoke__">get</span>(<span class="keyword">move</span> || <span class="keyword">async</span> {</span><br><span class="line"> (</span><br><span class="line"> StatusCode::OK,</span><br><span class="line"> <span class="title function_ invoke__">Json</span>(json!(<span class="keyword">self</span>.<span class="title function_ invoke__">clone</span>().<span class="title function_ invoke__">tree</span>(<span class="keyword">self</span>.<span class="title function_ invoke__">clone</span>().root))),</span><br><span class="line"> )</span><br><span class="line"> }),</span><br><span class="line"> )]</span><br><span class="line"> }</span><br><span class="line">...</span><br></pre></td></tr></table></figure> - <p>编译错误:</p> <figure class="highlight text"><table><tr><td class="code"><pre><span class="line">error: lifetime may not live long enough</span><br><span class="line"> --> src/storage/filesystem/mod.rs:45:34</span><br><span class="line"> |</span><br><span class="line">45 | routing::get(move || async {</span><br><span class="line"> | __________________________-------_^</span><br><span class="line"> | | | |</span><br><span class="line"> | | | return type of closure `{async block@src/storage/filesystem/mod.rs:45:34: 50:14}` contains a lifetime `'2`</span><br><span class="line"> | | lifetime `'1` represents this closure's body</span><br><span class="line">46 | | (</span><br><span class="line">47 | | StatusCode::OK,</span><br><span class="line">48 | | Json(json!(self.clone().tree(self.clone().root))),</span><br><span class="line">49 | | )</span><br><span class="line">50 | | }),</span><br><span class="line"> | |_____________^ returning this value requires that `'1` must outlive `'2`</span><br><span class="line"> |</span><br><span class="line"> = note: closure implements `Fn`, so references to captured variables can't escape the closure</span><br></pre></td></tr></table></figure> - <p>这是因为 <code>handlers</code> 里面的闭包捕获了一个引用,并且尝试返回一个包含该引用的值导致的。</p> <p>细说就是:闭包内部使用了 <code>self.clone()</code> 来获取一个新的实例,然后在异步块中返回一个 JSON 对象,这个 JSON 对象依赖于 <code>self.tree()</code> 的结果。因为闭包捕获了 <code>self</code> 的引用,所以它必须保证 <code>self</code> 在闭包执行完毕后仍然有效。</p> -<p>解决这个问题的思路是:确保闭包中的所有引用都在闭包执行完毕之前就不再被使用。<br>就是说,要将闭包的作用域限制在一个更短的生命周期内,或者使用其他方式来避免闭包捕获长期存在的引用:</p> +<p>解决这个问题的思路是:确保闭包中的所有引用都在闭包执行完毕之前就不再被使用。<br> +就是说,要将闭包的作用域限制在一个更短的生命周期内,或者使用其他方式来避免闭包捕获长期存在的引用:</p> <figure class="highlight rust"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line">...</span><br><span class="line"> <span class="keyword">fn</span> <span class="title function_">handlers</span>(<span class="keyword">self</span>) <span class="punctuation">-></span> crate::server::request::Handlers {</span><br><span class="line"> <span class="keyword">let</span> <span class="variable">tree</span> = json!(<span class="keyword">self</span>.<span class="title function_ invoke__">clone</span>().<span class="title function_ invoke__">tree</span>(<span class="keyword">self</span>.<span class="title function_ invoke__">clone</span>().root));</span><br><span class="line"> <span class="built_in">vec!</span>[(</span><br><span class="line"> <span class="string">"/tree"</span>,</span><br><span class="line"> routing::<span class="title function_ invoke__">get</span>(<span class="keyword">move</span> || <span class="keyword">async</span> { (StatusCode::OK, <span class="title function_ invoke__">Json</span>(tree)) }),</span><br><span class="line"> )]</span><br><span class="line"> }</span><br><span class="line">...</span><br></pre></td></tr></table></figure>]]></content> <tags> <tag>Technique</tag> @@ -2014,11 +2212,8 @@ await prisma.$transaction(async tx => { <li>不安全的资源管理: 例如,传统的 <code>try-with-resources</code> 模式旨在确保资源在使用后被正确关闭。Capture Checking 通过跟踪与资源相关的 Capabilities,可以防止在资源关闭或失效后继续使用它的情况。文档中提到的 <code>usingLogFile</code> 示例就展示了这一点,其中一个闭包尝试写入一个已经关闭的文件,而Capture Checking可以捕获这种不安全的操作:</li> </ul> <figure class="highlight scala"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">usingLogFile</span></span>[<span class="type">T</span>](op: <span class="type">FileOutputStream</span> => <span class="type">T</span>): <span class="type">T</span> =</span><br><span class="line"> <span class="keyword">val</span> logFile = <span class="type">FileOutputStream</span>(<span class="string">"log"</span>)</span><br><span class="line"> <span class="keyword">val</span> result = op(logFile)</span><br><span class="line"> logFile.close()</span><br><span class="line"> result</span><br></pre></td></tr></table></figure> - <figure class="highlight scala"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">usingLogFile</span></span>[<span class="type">T</span>](op: <span class="type">FileOutputStream</span>^ => <span class="type">T</span>): <span class="type">T</span> =</span><br><span class="line"> <span class="comment">// same body as before</span></span><br></pre></td></tr></table></figure> - <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">| val later = usingLogFile { f => () => f.write(0) }</span><br><span class="line">| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^</span><br><span class="line">|The expression's type () => Unit is not allowed to capture the root capability `cap`.</span><br><span class="line">|This usually means that a capability persists longer than its allowed lifetime.</span><br></pre></td></tr></table></figure> - <ul> <li>Effect Polymorphism: Capture Checking 提供了一种更灵活和精确地推理和控制副作用的机制。它可以被视为一种 Effect system,允许类型系统跟踪和控制代码可能产生的副作用。</li> <li>“函数的颜色”问题: 在异步编程中,区分同步和异步操作一直是一个挑战。Capture Checking 有可能帮助区分和管理同步与异步计算,这通过跟踪与异步操作相关的 Capabilities 来实现。</li> @@ -2032,15 +2227,13 @@ await prisma.$transaction(async tx => { <p>开发者还可以指定函数可以捕获的特定 Capability,语法为 <code>A ->{c, d} B</code>,表示该函数可以捕获 Capability <code>c</code> 和 <code>d</code>。这种语法允许对函数可以使用的Capability 进行精确控制,从而提高了资源管理的细粒度。通过显式列出捕获的 Capability,编译器可以验证函数是否遵守这些约束,并防止其意外访问其他资源。</p> <p>捕获注解 <code>^</code> 的优先级高于 <code>-></code> 。理解运算符的优先级对于正确解释和编写带有捕获注解的函数类型至关重要。不正确的解析可能导致意想不到的行为或类型错误。例如,<code>A ^ C -> B</code> 表示一个从捕获的 <code>A</code> 到 <code>B</code> 的纯函数。</p> <figure class="highlight scala"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">f</span></span>(x: ->{c} <span class="type">Int</span>): <span class="type">Int</span></span><br></pre></td></tr></table></figure> - <p>Capture Checking 也适用于上下文函数。不纯的上下文函数使用 <code>?=></code>,行为类似于 <code>=></code>,可以捕获任意Capability。纯的上下文函数使用 <code>?-></code>,行为类似于 <code>-></code>,不能捕获任何Capability。这表明,Capture Checking扩展到了上下文函数,允许控制在它们的隐式参数作用域内捕获的 Capability。</p> <p>值得注意的是,方法本身并不是值,因此它们不直接捕获Capability。相反,它们对 Capability 的引用会被计入封闭对象的捕获集中。这种区分很重要,因为方法的捕获行为与它们所属对象的状态和Capability相关联,这反映了 Scala 的面向对象特性。</p> <p>与函数类型类似,Capture Checking的概念也延伸到了命名参数类型。<code>=> Int</code> 允许任意Capability引用,类似于不纯函数类型。<code>-> Int</code> 禁止任何Capability引用,类似于纯函数类型。而 <code>->{c} Int</code> 则只允许引用Capability <code>c</code>。这种一致性确保了即使是延迟求值的表达式也遵循Capability约束。</p> <p>子捕获(<code>C₁ <: C₂</code>)定义了捕获集之间的关系。捕获集 <code>C₁</code> 是 <code>C₂</code> 的子类型,如果 <code>C₂</code> 包含了 <code>C₁</code> 中的每一个元素,并且满足以下条件之一:<code>c ∈ C₂</code>(直接包含);<code>c</code> 是一个类参数,且 <code>C₂</code> 包含 <code>Cls.this</code>(Capability 来源于封闭的类实例);<code>c</code> 的类型具有捕获集 <code>C</code>,且 <code>C <: C₂</code>(基于 Capability 类型的递归子捕获)。子捕获定义了 Capability 依赖的层级结构,这对于类型系统判断一个需要特定 Capability 集合的值是否可以在提供不同 Capability 集合的上下文中使用至关重要。</p> <p>对于捕获类型的子类型,存在以下规则:纯类型是捕获类型的子类型(<code>T <: C T</code>);较小的捕获集会产生子类型(如果 <code>C₁ <: C₂</code> 且 <code>T₁ <: T₂</code>,则 <code>C₁ T₁ <: C₂ T₂</code>)。这意味着一个依赖较少 Capability 的值通常更通用,可以在更广泛的场景中使用。根 Capability <code>{cap}</code> 覆盖了所有其他捕获集,因此任何特定的捕获集都是 <code>{cap}</code> 的子类型。这允许具有特定捕获要求的类型在允许任何 Capability 的上下文中使用。</p> -<p>Capability widening(也称为 _avoidance_)是一种简化局部变量类型的机制。局部变量的类型会被 widening 到不提及该变量本身的最小超类型,这个过程通常会涉及到变量的捕获集。这种加宽有助于改善类型推断和代码清晰度,避免局部变量的类型变得过于复杂。</p> +<p>Capability widening(也称为 <em>avoidance</em>)是一种简化局部变量类型的机制。局部变量的类型会被 widening 到不提及该变量本身的最小超类型,这个过程通常会涉及到变量的捕获集。这种加宽有助于改善类型推断和代码清晰度,避免局部变量的类型变得过于复杂。</p> <figure class="highlight scala"><table><tr><td class="code"><pre><span class="line">fs: <span class="type">FileSystem</span>^</span><br><span class="line">ct: <span class="type">CanThrow</span>[<span class="type">Exception</span>]^</span><br><span class="line">l : <span class="type">Logger</span>^{fs}</span><br><span class="line"></span><br><span class="line">{l} <: {fs} <: {cap}</span><br><span class="line">{fs} <: {fs, ct} <: {cap}</span><br><span class="line">{ct} <: {fs, ct} <: {cap}</span><br></pre></td></tr></table></figure> - <p>继承自 <code>caps.Capability</code> 的类具有隐式的 <code>{cap}</code> 捕获集。这表明这些类的实例本质上代表了一种 Capability。Capability 类提供了一种将 Capability 显式定义和管理为类型系统中的一等公民的方式。开发者可以创建具有特定语义和使用模式的自定义 Capability。</p> <p>在使用 Capability 类的场景中,通常会结合 using clauses 和隐式参数来减少在代码中显式传递 Capability 的需要。这两种方法提供了一种自动将必要的 Capability 提供给函数和方法的方式,从而减少了样板代码并提高了代码的可读性。</p> <p>闭包会捕获在其主体中引用的来自其周围环境的 Capability。这导致闭包的函数类型中包含捕获集。例如,如果一个闭包引用了一个局部变量 <code>fs</code>,而 <code>fs</code> 是一个 Capability,那么该闭包的类型可能就是 <code>String ->{fs} Unit</code>。这意味着闭包继承了其封闭代码的 Capability 要求,确保它们只能在这些 Capability 可用的上下文中被使用。</p> @@ -2050,10 +2243,7 @@ await prisma.$transaction(async tx => { <p>类的捕获引用包括从类外部使用的局部 Capability 以及具有捕获类型的构造函数参数(参数Capability)。局部Capability会被内部类继承。</p> <p>类实例的 <code>this</code> 的捕获集是根据捕获的引用、父类以及类内部的使用约束来推断的 1。这种自动推断机制在很多情况下减少了手动指定类捕获集的需要。</p> <figure class="highlight scala"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> caps.<span class="type">Capability</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">FileSystem</span> <span class="keyword">extends</span> <span class="title">Capability</span></span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Logger</span>(<span class="params">using <span class="type">FileSystem</span></span>)</span>:</span><br><span class="line"> <span class="function"><span class="keyword">def</span> <span class="title">log</span></span>(s: <span class="type">String</span>): <span class="type">Unit</span> = ???</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">test</span></span>(<span class="keyword">using</span> fs: <span class="type">FileSystem</span>) =</span><br><span class="line"> <span class="keyword">val</span> l: <span class="type">Logger</span>^{fs} = <span class="type">Logger</span>()</span><br><span class="line"> ...</span><br></pre></td></tr></table></figure> - <figure class="highlight scala"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Logger</span>(<span class="params">using <span class="type">FileSystem</span>^{cap}</span>)</span>:</span><br><span class="line"> ^^^^^^^^^^^^^^</span><br><span class="line"> redundant capture: <span class="type">FileSystem</span> already accounts <span class="keyword">for</span> cap</span><br></pre></td></tr></table></figure> - - <p>捕获隧道 (Capture Tunnelling) 是指当一个类型变量被一个捕获类型实例化时,捕获信息不会立即传播到外层的泛型类型。相反,捕获会“穿过隧道”,并在类型变量被访问或其成员被使用时重新出现。这种机制有助于以更简洁和可管理的方式处理泛型代码中的捕获集,避免类型签名过于复杂。</p> <p>逃逸检查施加了一些限制。作为类型变量实例的捕获类型不能携带通用Capability <code>cap</code> 。可变变量也不能拥有通用捕获集 。逃逸检查阻止了在参数化类型的参数中返回或分配带有局部 Capability 的闭包,因为这可能导致 Capability 逃逸其预期的作用域。单调性规则指出,在一个带有字段 <code>f</code> 的类中,<code>{this}</code> 覆盖了 <code>{this.f}</code> 以及 <code>this.f</code> 对纯参数的应用。这意味着如果类实例本身被视为一种 Capability,那么其字段所持有的任何 Capability 也会被隐式地覆盖。逃逸检查对于维护 Capability 跟踪的完整性至关重要,它可以防止 Capability 在其预期生命周期或作用域之外被使用,尤其是在泛型和可变状态的上下文中。</p> <p>受检异常可以通过导入 <code>language.experimental.saferExceptions</code> 来启用。方法上的 <code>throws</code> 子句会扩展为一个隐式的 <code>CanThrow</code> Capability参数,表明该方法可能抛出指定类型的异常。<code>throw</code> 表达式需要 <code>CanThrow</code> Capability,而 <code>try</code> 表达式会创建这种Capability。在 <code>language.experimental.captureChecking</code> 下,由于逃逸的 Capability 而导致未处理异常的代码会被拒绝。为了实现这种集成,<code>CanThrow</code> 需要继承 <code>Capability</code>,并且需要将逃逸检查扩展到 <code>try</code> 表达式,以防止捕获 <code>cap</code>。Capture Checking 与受检异常的集成确保了异常的可能性也被作为一种 Capability 需求来跟踪,从而加强了语言的整体资源管理和错误处理 Capability。</p> @@ -2069,7 +2259,8 @@ await prisma.$transaction(async tx => { <th></th> </tr> </thead> -<tbody><tr> +<tbody> +<tr> <td>代码片段</td> <td>演示概念</td> <td>捕获行为解释</td> @@ -2139,7 +2330,8 @@ await prisma.$transaction(async tx => { <td>使用Capability多态的类型定义</td> <td>类型 <code>Source</code> 被参数化为可以持有Capability集 <code>X^</code>。</td> </tr> -</tbody></table> +</tbody> +</table> <p>当 <code>cap</code> 出现在函数的结果类型中时,通常表示一个由存在性量词绑定的未知类型(例如,<code>() -> Iterator^</code> 意味着 <code>() -> Exists x. Iterator^x</code>)。这表明返回的迭代器可能捕获了某种 Capability,但具体的哪种 Capability 在静态类型检查时是未知的。在内部,这种存在性 Capability 使用带有 sealed trait <code>Exists</code> 的依赖函数类型来表示 。结果类型中协变的 <code>cap</code> 会被替换为一个新的 existential variable。当应用一个具有 existential result 类型 <code>Exists ex.T</code> 的函数时,结果是 <code>T</code>,其中 <code>ex</code> 被 <code>cap</code> 替换。Existential Capability 允许类型系统表达在编译时具体捕获的 Capability 未知的情况,从而提供了灵活性,同时仍然保持了一定程度的跟踪。</p> <p>Reach Capability 用于表达一个变量引用了通过另一个Capability“Reach”的任何操作。例如,如果 <code>ops</code> 是一个表示一组操作的Capability,那么 <code>ops*</code> 就表示出现在 <code>ops</code> 类型中且通过 <code>ops</code> 访问的任何协变 Capability。Reach Capability 提供了一种间接推理和跟踪 Capability 的方式,这对于建模具有相互连接资源的复杂系统非常有用。</p> <p>Capability 多态允许使用带有上界 <code>CapSet</code> 的类型变量来参数化操作的捕获集。这使得定义诸如 <code>Source[X^]</code> 这样的类型成为可能,其中 <code>X^</code> 表示监听器可以持有的一组 Capability。Capability 多态增强了代码的表达性和可重用性,因为它允许函数和数据结构在它们可能依赖的 Capability 集上进行参数化。</p> @@ -2155,25 +2347,31 @@ await prisma.$transaction(async tx => { <title>TDD 和 DDD 的一些小想法</title> <url>/2025/03/20/TDD-%E5%92%8C-DDD-%E7%9A%84%E4%B8%80%E4%BA%9B%E5%B0%8F%E6%83%B3%E6%B3%95/</url> <content><![CDATA[<p>Test-Driven Development (TDD) 和 Domain-Driven Design (DDD) 是两种不同的软件开发方法论,各自有其独特的优缺点和应用场景。</p> -<h3 id="Test-Driven-Development-TDD"><a href="#Test-Driven-Development-TDD" class="headerlink" title="Test-Driven Development (TDD)"></a>Test-Driven Development (TDD)</h3><h4 id="优点:"><a href="#优点:" class="headerlink" title="优点:"></a>优点:</h4><ol> +<h3 id="Test-Driven-Development-TDD"><a class="header-anchor" href="#Test-Driven-Development-TDD">¶</a>Test-Driven Development (TDD)</h3> +<h4 id="优点:"><a class="header-anchor" href="#优点:">¶</a>优点:</h4> +<ol> <li>提高代码质量:通过编写测试来驱动开发,可以确保代码的正确性和可靠性。</li> <li>减少缺陷:早期发现和修复缺陷,减少后期的调试和维护成本。</li> <li>促进可维护性:代码更加模块化和可测试,便于后续的维护和扩展。</li> <li>文档化:测试代码本身就是一种文档,描述了系统的行为和期望。</li> <li>提高开发速度:虽然初期可能会慢一些,但长期来看,由于减少了重构和调试的时间,开发速度会提高。</li> </ol> -<h4 id="缺点:"><a href="#缺点:" class="headerlink" title="缺点:"></a>缺点:</h4><ol> +<h4 id="缺点:"><a class="header-anchor" href="#缺点:">¶</a>缺点:</h4> +<ol> <li>初期投入大:需要在开发前编写测试,初期投入的时间和精力较大。</li> <li>学习曲线陡峭:对新手开发者来说,学习和掌握TDD需要一定的时间。</li> <li>过度依赖测试:可能导致过度依赖单元测试,忽略了系统的整体性能和用户体验。</li> </ol> -<h3 id="Domain-Driven-Design-DDD"><a href="#Domain-Driven-Design-DDD" class="headerlink" title="Domain-Driven Design (DDD)"></a>Domain-Driven Design (DDD)</h3><h4 id="优点:-1"><a href="#优点:-1" class="headerlink" title="优点:"></a>优点:</h4><ol> +<h3 id="Domain-Driven-Design-DDD"><a class="header-anchor" href="#Domain-Driven-Design-DDD">¶</a>Domain-Driven Design (DDD)</h3> +<h4 id="优点:-v2"><a class="header-anchor" href="#优点:-v2">¶</a>优点:</h4> +<ol> <li>聚焦领域:通过深入理解业务领域,确保软件系统与业务需求紧密结合。</li> <li>模型驱动:建立一个清晰的领域模型,帮助开发者和业务专家共同理解系统。</li> <li>可维护性:通过明确的领域模型和边界,系统结构更加清晰,便于维护和扩展。</li> <li>沟通桥梁:提供了一种通用的语言(Ubiquitous Language),促进开发团队和业务团队之间的沟通。</li> </ol> -<h4 id="缺点:-1"><a href="#缺点:-1" class="headerlink" title="缺点:"></a>缺点:</h4><ol> +<h4 id="缺点:-v2"><a class="header-anchor" href="#缺点:-v2">¶</a>缺点:</h4> +<ol> <li>复杂性高:DDD方法论较为复杂,需要深入理解领域模型和设计模式。</li> <li>初期投入大:需要大量的时间和精力进行领域分析和建模。</li> <li>适用范围有限:对于简单的系统或小型项目,DDD可能显得过于复杂和冗余。</li> @@ -2188,23 +2386,27 @@ await prisma.$transaction(async tx => { <entry> <title>Turborepo 简述</title> <url>/2024/09/27/Turborepo-%E7%AE%80%E8%BF%B0/</url> - <content><![CDATA[<h2 id="Turborepo-简介"><a href="#Turborepo-简介" class="headerlink" title="Turborepo 简介"></a>Turborepo 简介</h2><p>Monorepos 有很多优势,但它们难以扩展。每个工作区都有自己的测试套件、自己的 linting 和构建过程。单个 monorepo 可能有数千个任务要执行。</p> + <content><![CDATA[<h2 id="Turborepo-简介"><a class="header-anchor" href="#Turborepo-简介">¶</a>Turborepo 简介</h2> +<p>Monorepos 有很多优势,但它们难以扩展。每个工作区都有自己的测试套件、自己的 linting 和构建过程。单个 monorepo 可能有数千个任务要执行。</p> <p>Turborepo 是一个专为 JavaScript 和 TypeScript 代码库设计的构建系统,旨在优化 monorepos 和 single-package workspace 中的任务。它通过远程缓存(remote caching)和高效的任务调度(task scheduling)来解决 monorepos 中的扩展问题。Turborepo 也可以增量部署(adopted incrementally),并与各种包管理器配合使用。</p> <ul> <li>远程缓存: 存储所有任务的结果,CI 就不需要重复执行相同的工作了。</li> <li>任务调度:利用所有核心的性能并行处理任务,尽可能的加速。</li> </ul> <p><code>turbo</code> 基于 workspace 构建,workspaces 是 JavaScript 生态系统中包管理器的一项功能,允许将多个包分组到一个存储库中:</p> -<h3 id="Workspace"><a href="#Workspace" class="headerlink" title="Workspace"></a>Workspace</h3><p>在 JavaScript 中,Workspace 是指仓库中的特定实体,可以是<a href="https://vercel.com/docs/vercel-platform/glossary#single-package-workspace">单个包</a>或<a href="https://vercel.com/docs/vercel-platform/glossary#multi-package-workspace">包的集合</a>。<br>包管理器的 root lock 文件(例如 <code>pnpm-lock.yaml</code>)以及任何其他配置都位于 Wrokspace 的根目录。在 Monorepo 中可以有多个工作区,每个工作区位于存储库的子目录中。</p> -<h3 id="Single-package-workspace"><a href="#Single-package-workspace" class="headerlink" title="Single-package workspace"></a><a href="https://vercel.com/docs/vercel-platform/glossary#single-package-workspace">Single-package workspace</a></h3><p>只有一个独立包的工作区,在工作区根目录下有一个 <code>package.json</code> 文件。</p> -<h3 id="Multi-package-workspace"><a href="#Multi-package-workspace" class="headerlink" title="Multi-package workspace"></a><a href="https://vercel.com/docs/vercel-platform/glossary#multi-package-workspace">Multi-package workspace</a></h3><p>包含多个包的工作区,包含多个 <code>package.json</code> 文件,其中一个位于工作区根目录中用于全局配置,其他位于每个包目录中。</p> +<h3 id="Workspace"><a class="header-anchor" href="#Workspace">¶</a>Workspace</h3> +<p>在 JavaScript 中,Workspace 是指仓库中的特定实体,可以是<a href="https://vercel.com/docs/vercel-platform/glossary#single-package-workspace">单个包</a>或<a href="https://vercel.com/docs/vercel-platform/glossary#multi-package-workspace">包的集合</a>。<br> +包管理器的 root lock 文件(例如 <code>pnpm-lock.yaml</code>)以及任何其他配置都位于 Wrokspace 的根目录。在 Monorepo 中可以有多个工作区,每个工作区位于存储库的子目录中。</p> +<h3 id="Single-package-workspace"><a class="header-anchor" href="#Single-package-workspace">¶</a><a href="https://vercel.com/docs/vercel-platform/glossary#single-package-workspace">Single-package workspace</a></h3> +<p>只有一个独立包的工作区,在工作区根目录下有一个 <code>package.json</code> 文件。</p> +<h3 id="Multi-package-workspace"><a class="header-anchor" href="#Multi-package-workspace">¶</a><a href="https://vercel.com/docs/vercel-platform/glossary#multi-package-workspace">Multi-package workspace</a></h3> +<p>包含多个包的工作区,包含多个 <code>package.json</code> 文件,其中一个位于工作区根目录中用于全局配置,其他位于每个包目录中。</p> <blockquote> <p>这种类型的工作区通常称为 monorepo</p> </blockquote> <hr> <p>以 npm 为例,turbo 会初始化一个这样的目录结构使其成为有效的 workspace:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">|- package.json</span><br><span class="line">|- package-lock.json</span><br><span class="line">|- turbo.json</span><br><span class="line">|- apps</span><br><span class="line">|-- docs</span><br><span class="line">|--- package.json</span><br><span class="line">|-- web</span><br><span class="line">|--- package.json</span><br><span class="line">|- packages</span><br><span class="line">|--- ui</span><br></pre></td></tr></table></figure> - <p>一个 “有效的” turbo 项目至少要有:</p> <ul> <li>包管理器描述的包</li> @@ -2215,7 +2417,6 @@ await prisma.$transaction(async tx => { </ul> <p>例如,在根目录的 <code>package.json</code> 中配置:</p> <figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"workspaces"</span><span class="punctuation">:</span> <span class="punctuation">[</span></span><br><span class="line"> <span class="string">"apps/*"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="string">"packages/*"</span></span><br><span class="line"> <span class="punctuation">]</span></span><br><span class="line"><span class="punctuation">}</span></span><br></pre></td></tr></table></figure> - <p>那么 <code>apps</code> 或 <code>packages</code> 目录中有 <code>package.json</code> 的每个目录都将被视为一个包。</p> <blockquote> <p>注意:Turborepo 不支持嵌套包,例如 <code>apps/</code> 或 <code>packages/</code> 这种,将一个包放在<code>apps/a</code> 并将另一个包放在 <code>apps/a/b</code> 的结构将导致错误。</p> @@ -2223,10 +2424,10 @@ await prisma.$transaction(async tx => { </blockquote> <p>根目录的 <code>package.json</code> 是 workspace 的基础,常见的配置:</p> <figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"private"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">true</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"scripts"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"build"</span><span class="punctuation">:</span> <span class="string">"turbo run build"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"dev"</span><span class="punctuation">:</span> <span class="string">"turbo run dev"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"lint"</span><span class="punctuation">:</span> <span class="string">"turbo run lint"</span></span><br><span class="line"> <span class="punctuation">}</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"devDependencies"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"turbo"</span><span class="punctuation">:</span> <span class="string">"latest"</span></span><br><span class="line"> <span class="punctuation">}</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"packageManager"</span><span class="punctuation">:</span> <span class="string">"[email protected]"</span></span><br><span class="line"><span class="punctuation">}</span></span><br></pre></td></tr></table></figure> - <p>而根目录的 <code>turbo.json</code> 用于配置 <code>turbo</code> 的行为。那些 lock 文件是包管理器和 <code>turbo</code> 用于 reproducible 的关键。此外,Turborepo 还利用它们分析工作区中<a href="https://turbo.build/repo/docs/core-concepts/internal-packages">内部包</a>之间的依赖关系。</p> <hr> -<h3 id="包中的-package-json"><a href="#包中的-package-json" class="headerlink" title="包中的 package.json"></a>包中的 <code>package.json</code></h3><p><a href="https://nodejs.org/api/packages.html#name"><code>name</code> 字段</a>用于标识包。它在 workspace 中应该是唯一的。</p> +<h3 id="包中的-package-json"><a class="header-anchor" href="#包中的-package-json">¶</a>包中的 <code>package.json</code></h3> +<p><a href="https://nodejs.org/api/packages.html#name"><code>name</code> 字段</a>用于标识包。它在 workspace 中应该是唯一的。</p> <blockquote> <p>最佳做法是为<a href="https://turbo.build/repo/docs/core-concepts/internal-packages">内部包</a>使用命名空间前缀,以避免与 npm 注册表上的其他包发生冲突。例如,如果组织名为 <code>clin</code>,则可以将包命名为 <code>@clin/package-name</code>。</p> </blockquote> @@ -2234,10 +2435,8 @@ await prisma.$transaction(async tx => { <p><a href="https://nodejs.org/api/packages.html#exports"><code>exports</code> 字段</a>用于指定要使用该包的其他包的入口点。如果要在另一个包中使用一个包中的代码,将从该入口点导入。</p> <p>例如,如果有一个 <code>@repo/math</code> 包,则可以这么写 <code>exports</code> 字段:</p> <figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"exports"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"."</span><span class="punctuation">:</span> <span class="string">"./dist/constants.ts"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"./add"</span><span class="punctuation">:</span> <span class="string">"./dist/add.ts"</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"./subtract"</span><span class="punctuation">:</span> <span class="string">"./dist/subtract.ts"</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"><span class="punctuation">}</span></span><br></pre></td></tr></table></figure> - <p>然后就可以从 <code>@repo/math</code> 包中导入 <code>add</code> 和 <code>subtract</code> 函数了:</p> <figure class="highlight typescript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> { <span class="variable constant_">GRAVITATIONAL_CONSTANT</span>, <span class="variable constant_">SPEED_OF_LIGHT</span> } <span class="keyword">from</span> <span class="string">'@repo/math'</span>;</span><br><span class="line"><span class="keyword">import</span> { add } <span class="keyword">from</span> <span class="string">'@repo/math/add'</span>;</span><br><span class="line"><span class="keyword">import</span> { subtract } <span class="keyword">from</span> <span class="string">'@repo/math/subtract'</span>;</span><br></pre></td></tr></table></figure> - <p>以这种方式使用导出有三个主要好处:</p> <ul> <li>避免 barrel 文件:barrel 文件是重新导出同一包中其他文件的文件,从而为整个包创建一个入口点。虽然它们可能看起来很方便,但编译器<a href="https://vercel.com/blog/how-we-optimized-package-imports-in-next-js#what's-the-problem-with-barrel-files">和捆绑程序很难处理</a>它们,并且可能很快导致性能问题。</li> @@ -2249,12 +2448,11 @@ await prisma.$transaction(async tx => { <blockquote> <p>其他:包通常使用 <code>src</code> 目录来存储其源代码并编译到 <code>dist</code> 目录(也应位于包中)。</p> </blockquote> -<h2 id="管理依赖项"><a href="#管理依赖项" class="headerlink" title="管理依赖项"></a>管理依赖项</h2><figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"dependencies"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"next"</span><span class="punctuation">:</span> <span class="string">"latest"</span><span class="punctuation">,</span> <span class="comment">// 外部依赖</span></span><br><span class="line"> <span class="attr">"@repo/ui"</span><span class="punctuation">:</span> <span class="string">"*"</span> <span class="comment">// 内部依赖</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"><span class="punctuation">}</span></span><br></pre></td></tr></table></figure> - +<h2 id="管理依赖项"><a class="header-anchor" href="#管理依赖项">¶</a>管理依赖项</h2> +<figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"dependencies"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"next"</span><span class="punctuation">:</span> <span class="string">"latest"</span><span class="punctuation">,</span> <span class="comment">// 外部依赖</span></span><br><span class="line"> <span class="attr">"@repo/ui"</span><span class="punctuation">:</span> <span class="string">"*"</span> <span class="comment">// 内部依赖</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"><span class="punctuation">}</span></span><br></pre></td></tr></table></figure> <p>在存储库中安装依赖项时,应将其直接安装在使用它的软件包中。包的 <code>package.json</code> 将包含所需的每个依赖项。外部和内部依赖项都是如此。</p> <p>要在多个包中快速安装依赖项,可以:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">npm install jest --workspace=web --workspace=@repo/ui --save-dev</span><br></pre></td></tr></table></figure> - <p>这种做法有几个好处:</p> <ul> <li>更清晰:当软件包的依赖项列在其 <code>package.json</code> 中时,更容易理解软件包所依赖的内容。在存储库中工作的开发人员可以一目了然地看到包中使用了哪些依赖项。</li> @@ -2265,94 +2463,97 @@ await prisma.$transaction(async tx => { <blockquote> <p>属于工作区根目录的唯一依赖项是用于管理存储库的工具,而用于构建应用程序和库的依赖项安装在各自的包中。一些适合安装在根中的依赖项示例包括 <a href="https://www.npmjs.com/package/turbo"><code>turbo</code></a>、<a href="https://www.npmjs.com/package/husky"><code>husky</code></a> 或 <a href="https://www.npmjs.com/package/lint-staged"><code>lint-staged</code></a>。</p> </blockquote> -<h3 id="保持同一版本的依赖"><a href="#保持同一版本的依赖" class="headerlink" title="保持同一版本的依赖"></a>保持同一版本的依赖</h3><p>一些 monorepo 维护者更喜欢按照规则在所有软件包中保持对相同版本的依赖关系。有几种方法可以实现此目的:</p> +<h3 id="保持同一版本的依赖"><a class="header-anchor" href="#保持同一版本的依赖">¶</a>保持同一版本的依赖</h3> +<p>一些 monorepo 维护者更喜欢按照规则在所有软件包中保持对相同版本的依赖关系。有几种方法可以实现此目的:</p> <ul> <li>使用专用的工具,比如 <a href="https://www.npmjs.com/package/syncpack"><code>syncpack</code></a>、<a href="https://www.npmjs.com/package/@manypkg/cli"><code>manypkg</code></a> 和 <a href="https://www.npmjs.com/package/sherif"><code>sherif</code></a> 等工具可用于此特定目的。</li> -<li>或者单纯的使用包管理器,可以使用软件包管理器通过一个命令更新依赖项版本:<ul> +<li>或者单纯的使用包管理器,可以使用软件包管理器通过一个命令更新依赖项版本: +<ul> <li><code>npm install typescript@latest --workspaces</code></li> </ul> </li> <li>或者最粗暴的用编辑器一次查找并替换存储库中所有 <code>package.json</code> 文件的依赖项版本。用 <code>“next”: “.*”</code> 之类的正则表达式来查找并替换为所需的版本。完成后再运行包管理器的 install 命令来更新 lock 文件.</li> </ul> -<h2 id="内部包"><a href="#内部包" class="headerlink" title="内部包"></a>内部包</h2><p><a href="https://turbo.build/repo/docs/core-concepts/internal-packages">内部包</a>是工作区的构建块(building blocks),是一种在存储库中共享代码的强大方式。Turborepo 读取 <code>package.json</code> 中的依赖项来分析内部包之间的关系,并在后台创建 <a href="https://turbo.build/repo/docs/core-concepts/package-and-task-graph#package-graph">Package Graph</a> 以优化存储库的工作流程。</p> +<h2 id="内部包"><a class="header-anchor" href="#内部包">¶</a>内部包</h2> +<p><a href="https://turbo.build/repo/docs/core-concepts/internal-packages">内部包</a>是工作区的构建块(building blocks),是一种在存储库中共享代码的强大方式。Turborepo 读取 <code>package.json</code> 中的依赖项来分析内部包之间的关系,并在后台创建 <a href="https://turbo.build/repo/docs/core-concepts/package-and-task-graph#package-graph">Package Graph</a> 以优化存储库的工作流程。</p> <p>在创建内部包时,建议创建具有单一 “用途” 的包。这是最佳实践,具体取决于存储库的规模、组织、团队需求等。此策略具有以下几个优点:</p> <ul> <li>更易于理解:随着存储库的扩展,在存储库中工作的开发人员将能够更轻松地找到他们需要的代码。</li> <li>减少每个包的依赖项:每个包使用更少的依赖项,以便 Turborepo 可以更有效地<a href="https://turbo.build/repo/docs/reference/prune">修剪包图的依赖项</a>。</li> </ul> -<p>在创建<a href="https://turbo.build/repo/docs/core-concepts/package-types#application-packages">应用程序包</a>时,最好避免将共享代码放在这些包中。相反,应该为共享代码创建一个单独的包,并让应用程序包依赖于该包。<br>此外,应用程序包不应安装到其他包中。相反,应将它们视为 <a href="https://turbo.build/repo/docs/core-concepts/package-and-task-graph#package-graph">Package Graph</a> 的入口点。</p> -<h2 id="配置任务"><a href="#配置任务" class="headerlink" title="配置任务"></a>配置任务</h2><p>Turborepo 将始终按照 <a href="https://turbo.build/repo/docs/reference/configuration"><code>turbo.json</code> 配置</a>和 <a href="https://turbo.build/repo/docs/core-concepts/package-and-task-graph#package-graph">Package Graph</a> 中描述的顺序运行任务,并尽可能并行化工作以确保一切尽可能快地运行。</p> +<p>在创建<a href="https://turbo.build/repo/docs/core-concepts/package-types#application-packages">应用程序包</a>时,最好避免将共享代码放在这些包中。相反,应该为共享代码创建一个单独的包,并让应用程序包依赖于该包。<br> +此外,应用程序包不应安装到其他包中。相反,应将它们视为 <a href="https://turbo.build/repo/docs/core-concepts/package-and-task-graph#package-graph">Package Graph</a> 的入口点。</p> +<h2 id="配置任务"><a class="header-anchor" href="#配置任务">¶</a>配置任务</h2> +<p>Turborepo 将始终按照 <a href="https://turbo.build/repo/docs/reference/configuration"><code>turbo.json</code> 配置</a>和 <a href="https://turbo.build/repo/docs/core-concepts/package-and-task-graph#package-graph">Package Graph</a> 中描述的顺序运行任务,并尽可能并行化工作以确保一切尽可能快地运行。</p> <p>根目录的 <code>turbo.json</code> 文件是注册 Turborepo 将运行的任务的位置。定义任务后,将能够使用 <a href="https://turbo.build/repo/docs/reference/run"><code>turbo run</code></a> 运行一个或多个任务。</p> <p><code>tasks</code> 对象中的每个 key 都是一个可以通过 <code>turbo run</code> 执行的任务。Turborepo 将在 <code>package.json</code> 中搜索与任务同名的软件包:</p> <p><a href="https://turbo.build/repo/docs/reference/configuration#dependson"><code>dependsOn</code> 键</a>用于指定在其他任务开始运行之前必须完成的任务。在大多数情况下,库的<code>build</code>脚本在应用程序的<code>build</code>脚本运行之前完成,所以可以这么写:</p> <figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"tasks"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"build"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"dependsOn"</span><span class="punctuation">:</span> <span class="punctuation">[</span><span class="string">"^build"</span><span class="punctuation">]</span> </span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"><span class="punctuation">}</span></span><br></pre></td></tr></table></figure> - <blockquote> -<p><code>^</code> 这个语法告诉 Turborepo 从依赖关系图的底部开始运行任务。如果应用程序依赖于名为 <code>ui</code> 的库,并且该库具有<code>build</code>任务,则 <code>ui</code> 中的<code>build</code>脚本将首先运行。成功完成后,才会运行应用程序中的<code>build</code>任务。<br>这是一个重要的形式,因为它可以确保应用程序的<code>build</code>任务具有编译所需的所有必要依赖项。当依赖关系图发展到具有多个级别的任务依赖关系的更复杂的结构时,此概念也适用。</p> +<p><code>^</code> 这个语法告诉 Turborepo 从依赖关系图的底部开始运行任务。如果应用程序依赖于名为 <code>ui</code> 的库,并且该库具有<code>build</code>任务,则 <code>ui</code> 中的<code>build</code>脚本将首先运行。成功完成后,才会运行应用程序中的<code>build</code>任务。<br> +这是一个重要的形式,因为它可以确保应用程序的<code>build</code>任务具有编译所需的所有必要依赖项。当依赖关系图发展到具有多个级别的任务依赖关系的更复杂的结构时,此概念也适用。</p> </blockquote> <p>有时可能需要确保同一包中的两个任务按特定顺序运行。例如需要先在库中运行<code>build</code>任务,然后再在同一库中运行<code>test</code>任务。这种情况删掉 <code>^</code> 就行了:</p> <figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"tasks"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"test"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"dependsOn"</span><span class="punctuation">:</span> <span class="punctuation">[</span><span class="string">"build"</span><span class="punctuation">]</span> </span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"><span class="punctuation">}</span></span><br></pre></td></tr></table></figure> - <p>还可以在特定包中指定要依赖的单个任务。例如在任何 <code>lint</code> 任务之前运行 <code>utils</code> 中的<code>build</code>任务:</p> <figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"tasks"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"lint"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"dependsOn"</span><span class="punctuation">:</span> <span class="punctuation">[</span><span class="string">"utils#build"</span><span class="punctuation">]</span> </span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"><span class="punctuation">}</span></span><br></pre></td></tr></table></figure> - <p>或者更加细致的限定 <code>lint</code>:</p> <figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"tasks"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"web#lint"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"dependsOn"</span><span class="punctuation">:</span> <span class="punctuation">[</span><span class="string">"utils#build"</span><span class="punctuation">]</span> </span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"><span class="punctuation">}</span></span><br></pre></td></tr></table></figure> - <p>即 <code>Web 包中的</code> <code>lint</code> 任务只能在 <code>utils</code> 包中的<code>build</code>任务完成后运行。</p> <p>某些任务可能没有任何依赖项。例如用于在 Markdown 文件中查找拼写错误的任务可能不需要关心其他任务的状态。在这种情况下,省略 <code>dependsOn</code> 键或给个空数组就行了:</p> <figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"tasks"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"spell-check"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"dependsOn"</span><span class="punctuation">:</span> <span class="punctuation">[</span><span class="punctuation">]</span> </span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"><span class="punctuation">}</span></span><br></pre></td></tr></table></figure> - -<h3 id="指定输入输出"><a href="#指定输入输出" class="headerlink" title="指定输入输出"></a>指定输入输出</h3><p><code>outputs</code> 键告诉 Turborepo 文件和目录在任务成功完成时应该缓存在哪。如果未定义此 key,Turborepo 将不会缓存任何文件。</p> +<h3 id="指定输入输出"><a class="header-anchor" href="#指定输入输出">¶</a>指定输入输出</h3> +<p><code>outputs</code> 键告诉 Turborepo 文件和目录在任务成功完成时应该缓存在哪。如果未定义此 key,Turborepo 将不会缓存任何文件。</p> <p>例如缓存 vite 的输出一般可以这么写:</p> <figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"tasks"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"build"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"outputs"</span><span class="punctuation">:</span> <span class="punctuation">[</span><span class="string">"dist/"</span><span class="punctuation">]</span> </span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"><span class="punctuation">}</span></span><br></pre></td></tr></table></figure> - <p><code>inputs</code> 键用于指定要包含在任务哈希中以进行<a href="https://turbo.build/repo/docs/crafting-your-repository/caching">缓存</a>的文件。默认情况下,Turborepo 将包含包中由 Git 跟踪的所有文件。但是也可以使用 <code>inputs</code> 键更具体地说明哈希中包含哪些文件, 例如,在 Markdown 文件中查找拼写错误的任务可以定义如下::</p> <figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"tasks"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"spell-check"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"inputs"</span><span class="punctuation">:</span> <span class="punctuation">[</span><span class="string">"/*.md"</span><span class="punctuation">,</span> <span class="string">"/*.mdx"</span><span class="punctuation">]</span> </span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"><span class="punctuation">}</span></span><br></pre></td></tr></table></figure> - <p>可以通过微调 <code>input</code> 以忽略对已知不会影响任务输出的文件的更改来提高某些任务的缓存命中率, 可以使用 <code>$TURBO_DEFAULT$</code> 微语法来微调默认 <code>input</code> 行为:</p> <figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"tasks"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"build"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"inputs"</span><span class="punctuation">:</span> <span class="punctuation">[</span><span class="string">"$TURBO_DEFAULT$"</span><span class="punctuation">,</span> <span class="string">"!README.md"</span><span class="punctuation">]</span> </span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"><span class="punctuation">}</span></span><br></pre></td></tr></table></figure> - <p>这里 Turborepo 使用<code>build</code>任务的默认<code>input</code>,但会忽略对 <code>README.md</code> 文件的更改。如果 <code>README.md</code> 文件发生更改,任务仍将用上缓存。</p> -<h3 id="Root-任务"><a href="#Root-任务" class="headerlink" title="Root 任务"></a>Root 任务</h3><p>还可以使用 <code>turbo</code> 在 Workspace 根的 <code>package.json</code>中运行脚本。例如,除了每个软件包中的 <code>lint</code> 任务外,可能还需要对 Workspace 根目录中的文件运行 <code>lint:root</code> 任务:</p> +<h3 id="Root-任务"><a class="header-anchor" href="#Root-任务">¶</a>Root 任务</h3> +<p>还可以使用 <code>turbo</code> 在 Workspace 根的 <code>package.json</code>中运行脚本。例如,除了每个软件包中的 <code>lint</code> 任务外,可能还需要对 Workspace 根目录中的文件运行 <code>lint:root</code> 任务:</p> <figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"tasks"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"lint"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"dependsOn"</span><span class="punctuation">:</span> <span class="punctuation">[</span><span class="string">"^lint"</span><span class="punctuation">]</span></span><br><span class="line"> <span class="punctuation">}</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"//#lint:root"</span><span class="punctuation">:</span> <span class="punctuation">{</span><span class="punctuation">}</span> </span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"><span class="punctuation">}</span></span><br></pre></td></tr></table></figure> - -<h3 id="其他"><a href="#其他" class="headerlink" title="其他"></a>其他</h3><ul> -<li><p><a href="https://turbo.build/repo/docs/reference/package-configurations">包配置</a>是直接放入包中的<code>turbo.json</code>文件。这允许软件包为其自己的任务定义特定行为,而不会影响存储库的其余部分。</p> -</li> -<li><p>有一些始终需要运行的任务,例如缓存生成后的部署脚本。对于这些任务,用 <code>“cache”: false</code> :</p> +<h3 id="其他"><a class="header-anchor" href="#其他">¶</a>其他</h3> +<ul> +<li><a href="https://turbo.build/repo/docs/reference/package-configurations">包配置</a>是直接放入包中的<code>turbo.json</code>文件。这允许软件包为其自己的任务定义特定行为,而不会影响存储库的其余部分。</li> +<li>有一些始终需要运行的任务,例如缓存生成后的部署脚本。对于这些任务,用 <code>“cache”: false</code> :</li> +</ul> <figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"tasks"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"deploy"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"dependsOn"</span><span class="punctuation">:</span> <span class="punctuation">[</span><span class="string">"^build"</span><span class="punctuation">]</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"cache"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">false</span></span></span><br><span class="line"> <span class="punctuation">}</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"build"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"outputs"</span><span class="punctuation">:</span> <span class="punctuation">[</span><span class="string">"dist/"</span><span class="punctuation">]</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"><span class="punctuation">}</span></span><br></pre></td></tr></table></figure> -</li> -<li><p>某些任务可以并行运行,例如 Linter 不需要等待依赖项中的输出成功才能运行:</p> +<ul> +<li>某些任务可以并行运行,例如 Linter 不需要等待依赖项中的输出成功才能运行:</li> +</ul> <figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"tasks"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"transit"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"dependsOn"</span><span class="punctuation">:</span> <span class="punctuation">[</span><span class="string">"^transit"</span><span class="punctuation">]</span></span><br><span class="line"> <span class="punctuation">}</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"check-types"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"dependsOn"</span><span class="punctuation">:</span> <span class="punctuation">[</span><span class="string">"transit"</span><span class="punctuation">]</span></span><br><span class="line"> <span class="punctuation">}</span><span class="punctuation">,</span></span><br><span class="line"> <span class="punctuation">}</span><span class="punctuation">,</span></span><br><span class="line"><span class="punctuation">}</span></span><br></pre></td></tr></table></figure> <blockquote> <p>这里用到了 <a href="https://turbo.build/repo/docs/core-concepts/package-and-task-graph#transit-nodes">Transit Nodes</a> (就是名为 <code>transit</code> 的任务),这些 Transit Node 使用不执行任何操作的任务在软件包依赖项之间创建关系,这里用了名称 <code>transit</code>,但可以将任务命名为 Workspace 中尚未包含脚本的任何名称。</p> </blockquote> -</li> -</ul> -<h2 id="正在运行的任务"><a href="#正在运行的任务" class="headerlink" title="正在运行的任务"></a>正在运行的任务</h2><p>当在软件包的目录中时,<code>turbo</code> 会自动将命令范围限定为该软件包的 <a href="https://turbo.build/repo/docs/core-concepts/package-and-task-graph#package-graph">Package Graph</a>:</p> +<h2 id="正在运行的任务"><a class="header-anchor" href="#正在运行的任务">¶</a>正在运行的任务</h2> +<p>当在软件包的目录中时,<code>turbo</code> 会自动将命令范围限定为该软件包的 <a href="https://turbo.build/repo/docs/core-concepts/package-and-task-graph#package-graph">Package Graph</a>:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">cd apps/docs</span><br><span class="line">turbo build</span><br></pre></td></tr></table></figure> <p>将使用 <code>turbo.json</code> 中注册的<code>build</code>任务运行 <code>docs</code> 包的<code>build</code>任务。</p> <blockquote> <p>但也可以<a href="https://turbo.build/repo/docs/crafting-your-repository/running-tasks#using-filters">使用过滤器</a>覆盖 Automatic Package Scoping。</p> </blockquote> -<h3 id="运行多个任务"><a href="#运行多个任务" class="headerlink" title="运行多个任务"></a>运行多个任务</h3><p><code>Turbo</code> 能够运行多个任务,并尽可能并行化:</p> +<h3 id="运行多个任务"><a class="header-anchor" href="#运行多个任务">¶</a>运行多个任务</h3> +<p><code>Turbo</code> 能够运行多个任务,并尽可能并行化:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">turbo run build test lint check-types</span><br></pre></td></tr></table></figure> - -<h2 id="缓存"><a href="#缓存" class="headerlink" title="缓存"></a>缓存</h2><p>Turborepo 的缓存在本地工作时可以节省大量时间 - 启用<a href="https://turbo.build/repo/docs/core-concepts/remote-caching">远程缓存</a>时,它的功能更加强大,可在整个团队和 CI 之间共享缓存。</p> -<h3 id="缓存什么?"><a href="#缓存什么?" class="headerlink" title="缓存什么?"></a>缓存什么?</h3><ul> +<h2 id="缓存"><a class="header-anchor" href="#缓存">¶</a>缓存</h2> +<p>Turborepo 的缓存在本地工作时可以节省大量时间 - 启用<a href="https://turbo.build/repo/docs/core-concepts/remote-caching">远程缓存</a>时,它的功能更加强大,可在整个团队和 CI 之间共享缓存。</p> +<h3 id="缓存什么?"><a class="header-anchor" href="#缓存什么?">¶</a>缓存什么?</h3> +<ul> <li>在 <a href="https://turbo.build/repo/docs/reference/configuration#outputs"><code>turbo.json 的 outputs</code> 键</a>中定义的任务的文件输出。</li> <li>任务的终端输出,从任务第一次运行时开始将这些日志恢复到终端。</li> <li>对输入进行哈希处理,为任务运行创建一个 “fingerprints”。当 “fingerprints” 匹配时,运行任务将命中缓存。</li> </ul> -<h3 id="其他-1"><a href="#其他-1" class="headerlink" title="其他"></a>其他</h3><ul> +<h3 id="其他-v2"><a class="header-anchor" href="#其他-v2">¶</a>其他</h3> +<ul> <li><a href="https://turbo.build/repo/docs/reference/run#--dry----dry-run"><code>--dry</code> 标志</a>,可用于查看如果在没有实际运行任务的情况下运行任务会发生什么。当不确定正在运行的任务时,这对于调试缓存问题非常有用。</li> <li><a href="https://turbo.build/repo/docs/reference/run#--summarize"><code>--summarize</code> 标志</a>,可用于获取任务的所有输入、输出等的概览。比较两个摘要将揭示两个任务的哈希值不同的原因。</li> <li>强制 <code>turbo</code> 重新执行已缓存的任务,请使用 <a href="https://turbo.build/repo/docs/reference/run#--force"><code>--force</code> 标志</a>。请注意,这将禁用读取缓存,而不是写入。</li> </ul> -<h2 id="开发工作流"><a href="#开发工作流" class="headerlink" title="开发工作流"></a>开发工作流</h2><p>在 <code>turbo.json</code> 中定义开发任务 (development task) 会告诉 Turborepo 将运行一个长期任务。这对于运行开发服务器、运行测试或构建应用程序等操作非常有用:</p> +<h2 id="开发工作流"><a class="header-anchor" href="#开发工作流">¶</a>开发工作流</h2> +<p>在 <code>turbo.json</code> 中定义开发任务 (development task) 会告诉 Turborepo 将运行一个长期任务。这对于运行开发服务器、运行测试或构建应用程序等操作非常有用:</p> <figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"tasks"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"dev"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"cache"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">false</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"persistent"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">true</span></span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"><span class="punctuation">}</span></span><br></pre></td></tr></table></figure> - <ul> <li><code>"cache": false</code>:告诉 Turborepo 不要尝试缓存任务的结果。由于这是一项开发任务,可能会频繁更改代码,因此缓存结果没有用。</li> <li><code>"persistent": true</code>:告诉 Turborepo 保持任务运行,直到停止它。此键用作终端 UI 的信号,用于将任务视为长时间运行和交互式任务。此外,它还可以防止意外依赖不会退出的任务。</li> @@ -2360,13 +2561,13 @@ await prisma.$transaction(async tx => { <p>一些脚本允许使用 <code>stdin</code> 在其中键入以进行交互式输入。使用<a href="https://turbo.build/repo/docs/reference/configuration#ui">终端 UI</a>,可以选择一个任务,输入它,然后像往常一样使用 <code>stdin</code>。</p> <p>需要运行用于设置开发环境或预构建包的脚本。可以使用 <code>dependsOn</code> 确保这些任务在 <code>dev</code> 任务之前运行:</p> <figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"tasks"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"dev"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"cache"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">false</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"persistent"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">true</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"dependsOn"</span><span class="punctuation">:</span> <span class="punctuation">[</span><span class="string">"//#dev:setup"</span><span class="punctuation">]</span></span><br><span class="line"> <span class="punctuation">}</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"//#dev:setup"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"outputs"</span><span class="punctuation">:</span> <span class="punctuation">[</span><span class="string">".codegen/"</span><span class="punctuation">]</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"><span class="punctuation">}</span></span><br></pre></td></tr></table></figure> - <p>这里用的是 <a href="https://turbo.build/repo/docs/crafting-your-repository/configuring-tasks#registering-root-tasks">Root Task</a>,但可以对 <a href="https://turbo.build/repo/docs/crafting-your-repository/configuring-tasks#depending-on-a-specific-task-in-a-specific-package">packages 中的任意任务</a>使用相同的思路。</p> -<h3 id="Watch-mode"><a href="#Watch-mode" class="headerlink" title="Watch mode"></a>Watch mode</h3><p>许多工具都有一个内置的 watcher,比如 <a href="https://www.typescriptlang.org/docs/handbook/compiler-options.html#compiler-options"><code>tsc --watch</code></a>,它会响应源代码中的更改。有些则没有,<code>Turbo Watch</code> 为任何工具添加了依赖项感知的 Watcher。对源代码的更改将遵循在 <code>turbo.json</code> 中描述的 <a href="https://turbo.build/repo/docs/core-concepts/package-and-task-graph#task-graph">Task Graph (任务图</a>),例如:</p> +<h3 id="Watch-mode"><a class="header-anchor" href="#Watch-mode">¶</a>Watch mode</h3> +<p>许多工具都有一个内置的 watcher,比如 <a href="https://www.typescriptlang.org/docs/handbook/compiler-options.html#compiler-options"><code>tsc --watch</code></a>,它会响应源代码中的更改。有些则没有,<code>Turbo Watch</code> 为任何工具添加了依赖项感知的 Watcher。对源代码的更改将遵循在 <code>turbo.json</code> 中描述的 <a href="https://turbo.build/repo/docs/core-concepts/package-and-task-graph#task-graph">Task Graph (任务图</a>),例如:</p> <figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"tasks"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"dev"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"persistent"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">true</span></span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"cache"</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">false</span></span></span><br><span class="line"> <span class="punctuation">}</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"lint"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"dependsOn"</span><span class="punctuation">:</span> <span class="punctuation">[</span><span class="string">"^lint"</span><span class="punctuation">]</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"><span class="punctuation">}</span></span><br></pre></td></tr></table></figure> - <p>当运行 <code>turbo watch dev lint</code> 时,会看到每当更改源代码时,<code>lint</code> 脚本都会重新运行,尽管 ESLint 没有内置的 watcher。<code>Turbo Watch</code> 还知道内部依赖关系,因此 <code>@repo/UI</code> 中的代码更改将在 <code>@repo/UI</code> 和 <code>Web</code> 中重新运行任务。</p> -<h2 id="环境变量"><a href="#环境变量" class="headerlink" title="环境变量"></a>环境变量</h2><p>Turborepo 需要根据环境变量来决定是否改变应用程序的行为。在 <code>turbo.json</code> 文件中使用 <code>env</code> 和 <code>globalEnv</code> 键:</p> +<h2 id="环境变量"><a class="header-anchor" href="#环境变量">¶</a>环境变量</h2> +<p>Turborepo 需要根据环境变量来决定是否改变应用程序的行为。在 <code>turbo.json</code> 文件中使用 <code>env</code> 和 <code>globalEnv</code> 键:</p> <figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"globalEnv"</span><span class="punctuation">:</span> <span class="punctuation">[</span><span class="string">"IMPORTANT_GLOBAL_VARIABLE"</span><span class="punctuation">]</span><span class="punctuation">,</span></span><br><span class="line"> <span class="attr">"tasks"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"build"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"env"</span><span class="punctuation">:</span> <span class="punctuation">[</span><span class="string">"MY_API_URL"</span><span class="punctuation">,</span> <span class="string">"MY_API_KEY"</span><span class="punctuation">]</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"><span class="punctuation">}</span></span><br></pre></td></tr></table></figure> <ul> <li><code>globalEnv</code>:更改此列表中任何环境变量的值都将更改所有任务的哈希值。</li> @@ -2375,29 +2576,31 @@ await prisma.$transaction(async tx => { <blockquote> <p>Turborepo 会自动将前缀通配符添加到常见框架的 <a href="https://turbo.build/repo/docs/reference/configuration#env"><code>env</code></a> 键中 (### <a href="https://turbo.build/repo/docs/crafting-your-repository/using-environment-variables#framework-inference">Framework Inference</a>)</p> </blockquote> -<h3 id="Environment-mode"><a href="#Environment-mode" class="headerlink" title="Environment mode"></a>Environment mode</h3><p>Turborepo 的 Environment Mode 允许控制哪些环境变量在运行时可用于任务:</p> +<h3 id="Environment-mode"><a class="header-anchor" href="#Environment-mode">¶</a>Environment mode</h3> +<p>Turborepo 的 Environment Mode 允许控制哪些环境变量在运行时可用于任务:</p> <ul> <li><a href="https://turbo.build/repo/docs/crafting-your-repository/using-environment-variables#strict-mode">严格模式</a>(默认):将环境变量过滤为仅在 <code>turbo.json</code> 的 <code>env</code> 和 <code>globalEnv</code> 键中指定的环境变量。</li> <li><a href="https://turbo.build/repo/docs/crafting-your-repository/using-environment-variables#loose-mode">宽松模式</a>:允许进程的所有环境变量可用。</li> </ul> -<h3 id="其他-2"><a href="#其他-2" class="headerlink" title="其他"></a>其他</h3><ul> -<li><p><code>.env</code> 文件非常适合在本地处理应用程序。Turborepo 不会将 .env 文件加载到任务的运行时中,而是让它们由框架或 <a href="https://www.npmjs.com/package/dotenv"><code>dotenv</code></a> 等工具处理。但是,<code>turbo</code> 必须知道 <code>.env</code> 文件中值的更改,以便它可以将它们用于哈希。如果在两次构建之间更改 <code>.env</code> 文件中的变量,则 <code>build</code> 任务应该不会用上缓存。所以可以将其添加到 <code>input</code> 键中:</p> +<h3 id="其他-v3"><a class="header-anchor" href="#其他-v3">¶</a>其他</h3> +<ul> +<li><code>.env</code> 文件非常适合在本地处理应用程序。Turborepo 不会将 .env 文件加载到任务的运行时中,而是让它们由框架或 <a href="https://www.npmjs.com/package/dotenv"><code>dotenv</code></a> 等工具处理。但是,<code>turbo</code> 必须知道 <code>.env</code> 文件中值的更改,以便它可以将它们用于哈希。如果在两次构建之间更改 <code>.env</code> 文件中的变量,则 <code>build</code> 任务应该不会用上缓存。所以可以将其添加到 <code>input</code> 键中:</li> +</ul> <figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"globalDependencies"</span><span class="punctuation">:</span> <span class="punctuation">[</span><span class="string">".env"</span><span class="punctuation">]</span><span class="punctuation">,</span> <span class="comment">// All task hashes</span></span><br><span class="line"> <span class="attr">"tasks"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"build"</span><span class="punctuation">:</span> <span class="punctuation">{</span></span><br><span class="line"> <span class="attr">"inputs"</span><span class="punctuation">:</span> <span class="punctuation">[</span><span class="string">"$TURBO_DEFAULT$"</span><span class="punctuation">,</span> <span class="string">".env"</span><span class="punctuation">,</span> <span class="string">".env.local"</span><span class="punctuation">]</span> <span class="comment">// Only the `build` task hash</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"> <span class="punctuation">}</span></span><br><span class="line"><span class="punctuation">}</span></span><br></pre></td></tr></table></figure> -</li> -<li><p>不建议在存储库的根目录中使用 <code>.env</code> 文件。相反,建议将 <code>.env</code> 文件放入使用它们的包中。</p> -</li> -<li><p><a href="https://turbo.build/repo/docs/reference/eslint-config-turbo"><code>eslint-config-turbo</code> 软件包</a>可帮助查找代码中使用但未在 <code>turbo.json</code>中列出的环境变量。这有助于确保在配置中考虑所有环境变量。</p> -</li> -<li><p>Turborepo 在任务开始时对任务的环境变量进行哈希处理。如果在任务期间创建或更改环境变量,Turborepo 将不知道这些更改,也不会在任务哈希中考虑这些更改。</p> -</li> +<ul> +<li>不建议在存储库的根目录中使用 <code>.env</code> 文件。相反,建议将 <code>.env</code> 文件放入使用它们的包中。</li> +<li><a href="https://turbo.build/repo/docs/reference/eslint-config-turbo"><code>eslint-config-turbo</code> 软件包</a>可帮助查找代码中使用但未在 <code>turbo.json</code>中列出的环境变量。这有助于确保在配置中考虑所有环境变量。</li> +<li>Turborepo 在任务开始时对任务的环境变量进行哈希处理。如果在任务期间创建或更改环境变量,Turborepo 将不知道这些更改,也不会在任务哈希中考虑这些更改。</li> </ul> <hr> -<h2 id="最后"><a href="#最后" class="headerlink" title="最后"></a>最后</h2><ul> +<h2 id="最后"><a class="header-anchor" href="#最后">¶</a>最后</h2> +<ul> <li><a href="https://turbo.build/repo/docs/crafting-your-repository/constructing-ci">配置 CI</a></li> <li><a href="https://turbo.build/repo/docs/core-concepts">核心概念</a></li> </ul> <blockquote> -<p>本快速入门文档参照 Turborepo 2.x 官方文档: <a href="https://turbo.build/repo/docs">https://turbo.build/repo/docs</a><br>最后一次编辑:二〇二四年九月二十七日下午六点〇七分</p> +<p>本快速入门文档参照 Turborepo 2.x 官方文档: <a href="https://turbo.build/repo/docs">https://turbo.build/repo/docs</a><br> +最后一次编辑:二〇二四年九月二十七日下午六点〇七分</p> </blockquote> ]]></content> <tags> @@ -2412,32 +2615,26 @@ await prisma.$transaction(async tx => { </blockquote> <p>The first problem is, and personally, I believe it’s the biggest JavaScript problem ever: we don’t know what can throw an error. From a JavaScript error perspective, it’s the same as the following:</p> <figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">try</span> {</span><br><span class="line"> <span class="keyword">let</span> data = “<span class="title class_">Hello</span>”;</span><br><span class="line">} <span class="keyword">catch</span> (err) {</span><br><span class="line"> <span class="variable language_">console</span>.<span class="title function_">error</span>(err);</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - <p>JavaScript doesn’t know; JavaScript doesn’t care. You should know.</p> <p>Second thing, this is perfectly viable code:</p> <figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> request = { <span class="attr">name</span>: “test”, <span class="attr">value</span>: <span class="number">2n</span> };</span><br><span class="line"><span class="keyword">const</span> body = <span class="title class_">JSON</span>.<span class="title function_">stringify</span>(request);</span><br><span class="line"><span class="keyword">const</span> response = <span class="keyword">await</span> <span class="title function_">fetch</span>(<span class="string">"https://example.com"</span>, {</span><br><span class="line"> <span class="attr">method</span>: “<span class="variable constant_">POST</span>”,</span><br><span class="line"> body,</span><br><span class="line">});</span><br><span class="line"><span class="keyword">if</span> (!response.<span class="property">ok</span>) {</span><br><span class="line"> <span class="keyword">return</span>;</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - <p>No errors, no linters, even though this can break your app.</p> -<p>Right now, in my head, I can hear, “What’s the problem, just use try/catch everywhere.” Here comes the third problem: we don’t know which one is thrown. Of course, we can somehow guess by the error message, but what about bigger services/functions with many places where errors can happen? Are you sure you are handling all of them properly with one try/catch?</p> +<p>Right now, in my head, I can hear, “What’s the problem, just use try/catch everywhere.” Here comes the third problem: we don’t know which one is thrown. Of course, we can somehow guess by the error message, but what about bigger services/functions with many places where errors can happen? Are you sure you are handling all of them properly with one try/catch?</p> <hr> <figure class="highlight rust"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> <span class="variable">greeting_file_result</span> = File::<span class="title function_ invoke__">open</span>(“hello.txt”); </span><br><span class="line"><span class="keyword">let</span> <span class="variable">greeting_file</span> = <span class="keyword">match</span> greeting_file_result { </span><br><span class="line"> <span class="title function_ invoke__">Ok</span>(file) => file, </span><br><span class="line"> <span class="title function_ invoke__">Err</span>(error) => <span class="built_in">panic!</span>(<span class="string">"Problem opening the file: {:?}"</span>, error), </span><br><span class="line">};</span><br></pre></td></tr></table></figure> - <p>The most verbose of the three shown here and, ironically, the best one. So, first of all, Rust handles the errors using its amazing enums (they are not the same as TypeScript enums!). Without going into detail, what is important here is that it uses an enum called <code>Result</code> with two variants: <code>Ok</code> and <code>Err</code>. As you might guess, <code>Ok</code> holds a value and <code>Err</code> holds…surprise, an error :D.</p> <p>The summary here is that Rust always know where there might be an error. And it force you to deal with it right where it appears (mostly). No hidden ones, no guessing, no breaking app with a surprise face.</p> <p>And this approach is just better. By A MILE.</p> <p>We cannot make TypeScript errors work like the Rust. The limiting factor here is the language itself; it doesn’t have the proper tools to do that.</p> <p>But what we can do is try to make it similar. And make it simple:</p> <figure class="highlight typescript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">type</span> <span class="title class_">Safe</span><T> = </span><br><span class="line"> | { </span><br><span class="line"> <span class="attr">success</span>: <span class="literal">true</span>; </span><br><span class="line"> <span class="attr">data</span>: T; </span><br><span class="line"> } </span><br><span class="line"> | { </span><br><span class="line"> <span class="attr">success</span>: <span class="literal">false</span>; </span><br><span class="line"> <span class="attr">error</span>: <span class="built_in">string</span>; </span><br><span class="line"> };</span><br></pre></td></tr></table></figure> - -<p>we do need a few try/catches. The good thing is we only need about two, not 100,000:</p> +<p>we do need a few try/catches. The good thing is we only need about two, not 100,000:</p> <figure class="highlight typescript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">function</span> safe<T>(<span class="attr">promise</span>: <span class="title class_">Promise</span><T>, <span class="attr">err</span>?: <span class="built_in">string</span>): <span class="title class_">Promise</span><<span class="title class_">Safe</span><T>>;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">function</span> safe<T>(<span class="attr">func</span>: <span class="function">() =></span> T, <span class="attr">err</span>?: <span class="built_in">string</span>): <span class="title class_">Safe</span><T>;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">function</span> safe<T>(</span><br><span class="line"> <span class="attr">promiseOrFunc</span>: <span class="title class_">Promise</span><T> | (<span class="function">() =></span> T),</span><br><span class="line"> <span class="attr">err</span>?: <span class="built_in">string</span>,</span><br><span class="line">): <span class="title class_">Promise</span><<span class="title class_">Safe</span><T>> | <span class="title class_">Safe</span><T> {</span><br><span class="line"> <span class="keyword">if</span> (promiseOrFunc <span class="keyword">instanceof</span> <span class="title class_">Promise</span>) {</span><br><span class="line"> <span class="keyword">return</span> <span class="title function_">safeAsync</span>(promiseOrFunc, err);</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">return</span> <span class="title function_">safeSync</span>(promiseOrFunc, err);</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">async</span> <span class="keyword">function</span> safeAsync<T>(</span><br><span class="line"> <span class="attr">promise</span>: <span class="title class_">Promise</span><T>, </span><br><span class="line"> <span class="attr">err</span>?: <span class="built_in">string</span></span><br><span class="line">): <span class="title class_">Promise</span><<span class="title class_">Safe</span><T>> {</span><br><span class="line"> <span class="keyword">try</span> {</span><br><span class="line"> <span class="keyword">const</span> data = <span class="keyword">await</span> promise;</span><br><span class="line"> <span class="keyword">return</span> { data, <span class="attr">success</span>: <span class="literal">true</span> };</span><br><span class="line"> } <span class="keyword">catch</span> (e) {</span><br><span class="line"> <span class="variable language_">console</span>.<span class="title function_">error</span>(e);</span><br><span class="line"> <span class="keyword">if</span> (err !== <span class="literal">undefined</span>) {</span><br><span class="line"> <span class="keyword">return</span> { <span class="attr">success</span>: <span class="literal">false</span>, <span class="attr">error</span>: err };</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">if</span> (e <span class="keyword">instanceof</span> <span class="title class_">Error</span>) {</span><br><span class="line"> <span class="keyword">return</span> { <span class="attr">success</span>: <span class="literal">false</span>, <span class="attr">error</span>: e.<span class="property">message</span> };</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">return</span> { <span class="attr">success</span>: <span class="literal">false</span>, <span class="attr">error</span>: <span class="string">"Something went wrong"</span> };</span><br><span class="line"> }</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> safeSync<T>(</span><br><span class="line"> <span class="attr">func</span>: <span class="function">() =></span> T, </span><br><span class="line"> <span class="attr">err</span>?: <span class="built_in">string</span></span><br><span class="line">): <span class="title class_">Safe</span><T> {</span><br><span class="line"> <span class="keyword">try</span> {</span><br><span class="line"> <span class="keyword">const</span> data = <span class="title function_">func</span>();</span><br><span class="line"> <span class="keyword">return</span> { data, <span class="attr">success</span>: <span class="literal">true</span> };</span><br><span class="line"> } <span class="keyword">catch</span> (e) {</span><br><span class="line"> <span class="variable language_">console</span>.<span class="title function_">error</span>(e);</span><br><span class="line"> <span class="keyword">if</span> (err !== <span class="literal">undefined</span>) {</span><br><span class="line"> <span class="keyword">return</span> { <span class="attr">success</span>: <span class="literal">false</span>, <span class="attr">error</span>: err };</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">if</span> (e <span class="keyword">instanceof</span> <span class="title class_">Error</span>) {</span><br><span class="line"> <span class="keyword">return</span> { <span class="attr">success</span>: <span class="literal">false</span>, <span class="attr">error</span>: e.<span class="property">message</span> };</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">return</span> { <span class="attr">success</span>: <span class="literal">false</span>, <span class="attr">error</span>: <span class="string">"Something went wrong"</span> };</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - <p>This is just a wrapper with our <code>Safe</code> type as the return one. But sometimes simple things are all you need. Let’s combine them with the example from above.</p> <figure class="highlight typescript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> request = { <span class="attr">name</span>: “test”, <span class="attr">value</span>: <span class="number">2n</span> }; </span><br><span class="line"><span class="keyword">const</span> body = <span class="title function_">safe</span>( </span><br><span class="line"> <span class="function">() =></span> <span class="title class_">JSON</span>.<span class="title function_">stringify</span>(request), </span><br><span class="line"> “<span class="title class_">Failed</span> to serialize request”, </span><br><span class="line">); </span><br><span class="line"><span class="keyword">if</span> (!body.<span class="property">success</span>) { </span><br><span class="line"> <span class="comment">// handle error (body.error) </span></span><br><span class="line"> <span class="keyword">return</span>; </span><br><span class="line">} </span><br><span class="line"><span class="keyword">const</span> response = <span class="keyword">await</span> <span class="title function_">safe</span>( </span><br><span class="line"> <span class="title function_">fetch</span>(<span class="string">"https://example.com"</span>, { </span><br><span class="line"> <span class="attr">method</span>: “<span class="variable constant_">POST</span>”, </span><br><span class="line"> <span class="attr">body</span>: body.<span class="property">data</span>, </span><br><span class="line"> }), </span><br><span class="line">); </span><br><span class="line"><span class="keyword">if</span> (!response.<span class="property">success</span>) { </span><br><span class="line"> <span class="comment">// handle error (response.error) </span></span><br><span class="line"> <span class="keyword">return</span>; </span><br><span class="line">} </span><br><span class="line"><span class="keyword">if</span> (!response.<span class="property">data</span>.<span class="property">ok</span>) { </span><br><span class="line"> <span class="comment">// handle network error </span></span><br><span class="line"> <span class="keyword">return</span>; </span><br><span class="line">} </span><br><span class="line"><span class="comment">// handle response (body.data)</span></span><br></pre></td></tr></table></figure> - <p>New solution is longer, but it performs better because of the following reasons:</p> <ul> -<li>no try/catch</li> +<li>no try/catch</li> <li>we handle each error where it occurs</li> <li>we can specify an error message for a specific function</li> <li>we have a nice top-to-bottom logic, all errors on top, then only the response at the bottom</li> @@ -2450,30 +2647,35 @@ await prisma.$transaction(async tx => { <entry> <title>WiscKey: Separating Keys from Values in SSD-conscious Storage</title> <url>/2023/07/21/WiscKey-Separating-Keys-from-Values-in-SSD-conscious-Storage/</url> - <content><![CDATA[<p>We present WiscKey, a persistent LSM-tree-based key-value store with a performance-oriented data layoutthat separates keys from values to minimize I/O amplifi-cation. The design of WiscKey is highly SSD optimized, leveraging both the sequential and random performance characteristics of the device.</p> + <content><![CDATA[<p>We present WiscKey, a persistent LSM-tree-based key-value store with a performance-oriented data layoutthat separates keys from values to minimize I/O amplifi-cation. The design of WiscKey is highly SSD optimized, leveraging both the sequential and random performance characteristics of the device.</p> <ul> <li><a href="/papers/WiscKey:%20Separating%20Keys%20from%20Values%20in%20SSD-conscious%20Storage.pdf">原始论文</a></li> </ul> -<p>WiscKey是一种基于LSM-Tree的kv存储,它的实现很简单: 将键和值分开存储, 这么做可以显著的减少I/O放大。</p> +<p>WiscKey是一种基于LSM-Tree的kv存储,它的实现很简单: 将键和值分开存储, 这么做可以显著的减少I/O放大。</p> <p>WiscKey的设计是针对SSD优化的,充分利用了SSD的性能并提出了一种轻量的GC方案, 除此之外还分析了现代存储硬件的特性和LSM树的读写放大的问题。</p> <p>总的来说,WiscKey是基于SSD硬件特性而重新设计的存储结构。虽然LevelDB也是一种键值存储引擎,但它并没有像WiscKey那样专门为SSD硬件而设计。因此,如果将LevelDB的存储结构按照SSD硬件的特性进行优化,可能会提高一些性能,但是不一定能够达到WiscKey的性能水平。</p> -<h2 id="笔记"><a href="#笔记" class="headerlink" title="笔记"></a>笔记</h2><ul> -<li><p>The main data structures in LevelDB are an on-disk log file, two in-memory sorted skiplists (memtableand immutable memtable), and seven levels (L0 to L6) of on-disk Sorted String Table (SSTable) files</p> +<h2 id="笔记"><a class="header-anchor" href="#笔记">¶</a>笔记</h2> +<ul> +<li> +<p>The main data structures in LevelDB are an on-disk log file, two in-memory sorted skiplists (memtableand immutable memtable), and seven levels (L0 to L6) of on-disk Sorted String Table (SSTable) files</p> <blockquote> <p>LSM-trees的内部的各种组件可以使用任意索引结构来实现。通常内存组件会使用skiplist或B+树等并发数据结构,而磁盘组件会使用B+树或SSTables(SSTable包含一个数据块列表和一个索引块:数据块存储按键排序的键值对,索引块存储所有数据块的键范围)</p> </blockquote> </li> -<li><p>how LSM-trees maintainsequential I/O access by increasing I/O amplification.</p> +<li> +<p>how LSM-trees maintainsequential I/O access by increasing I/O amplification.</p> <blockquote> -<p>具体来说,LSM-trees的写放大是指每次写入操作都需要将数据追加到写前日志中,并加入到内存组件C0中。当C0的大小达到一定阈值时,C0会与磁盘上的C1进行归并排序操作,生成新的组件new-C1,并将其顺序写入磁盘,取代旧版本的C1。类似地,当C1的大小达到一定阈值时,C1会与下一层组件Ci+1合并。这种归并排序的过程可以保证数据在磁盘上的存储是有序的,从而保持顺序I/O访问</p> +<p>具体来说,LSM-trees的写放大是指每次写入操作都需要将数据追加到写前日志中,并加入到内存组件C0中。当C0的大小达到一定阈值时,C0会与磁盘上的C1进行归并排序操作,生成新的组件new-C1,并将其顺序写入磁盘,取代旧版本的C1。类似地,当C1的大小达到一定阈值时,C1会与下一层组件Ci+1合并。这种归并排序的过程可以保证数据在磁盘上的存储是有序的,从而保持顺序I/O访问</p> </blockquote> </li> -<li><p>First, WiscKey separates keys from values, keeping only keys in theLSM-tree and the values in a separate log file. Second,to deal with unsorted values (which necessitate random access during range queries), WiscKey uses the parallel random-read characteristic of SSD devices. Third, WiscKey utilizes unique crash-consistency and garbage-collection techniques to efficiently manage the value log.Finally, WiscKey optimizes performance by removingthe LSM-tree log without sacrificing consistency, thusreducing system-call overhead from small writes.</p> +<li> +<p>First, WiscKey separates keys from values, keeping only keys in theLSM-tree and the values in a separate log file. Second,to deal with unsorted values (which necessitate random access during range queries), WiscKey uses the parallel random-read characteristic of SSD devices. Third, WiscKey utilizes unique crash-consistency and garbage-collection techniques to efficiently manage the value log.Finally, WiscKey optimizes performance by removingthe LSM-tree log without sacrificing consistency, thusreducing system-call overhead from small writes.</p> <blockquote> <p>这是WiscKey的主要优化方式</p> </blockquote> </li> -<li><p>For range queries, LevelDB provides the user with an iterator-based interface with Seek(key), Next(), Prev(),Key() and Value() operations. To scan a range of key-value pairs, users can first Seek() to the starting key, then call Next() or Prev() to search keys one by one. To retrieve the key or the value of the current iterator position, users call Key() or Value(), respectively.</p> +<li> +<p>For range queries, LevelDB provides the user with an iterator-based interface with Seek(key), Next(), Prev(),Key() and Value() operations. To scan a range of key-value pairs, users can first Seek() to the starting key, then call Next() or Prev() to search keys one by one. To retrieve the key or the value of the current iterator position, users call Key() or Value(), respectively.</p> <blockquote> <p>如果要查询某个key范围的数据,LevelDB会先找到该范围的起始key在哪个SSTable中,然后按照顺序读取该SSTable中的数据,直到读取到范围之外的key为止。</p> <p>而读取SSTable中的数据是通过Binary Search来实现的。为了加速Search,LevelDB为每个SSTable建立了一个稀疏索引,用来记录每个数据块的最大key和最小key。</p> @@ -2490,19 +2692,17 @@ await prisma.$transaction(async tx => { <url>/2023/06/28/caml-release-runtime-system%E5%AF%BC%E8%87%B4%E7%9A%84%E6%AD%BB%E9%94%81%E9%97%AE%E9%A2%98/</url> <content><![CDATA[<p>给出一个<code>test.ml</code>:</p> <figure class="highlight ocaml"><table><tr><td class="code"><pre><span class="line"><span class="type">Printf</span>.eprintf <span class="string">"hello from OCaml\n%!"</span></span><br></pre></td></tr></table></figure> - <p>和<code>test-ocaml-5.c</code>:</p> <figure class="highlight c"><table><tr><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string"><stdio.h></span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string"><stdlib.h></span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string"><caml/misc.h></span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string"><caml/callback.h></span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string"><caml/threads.h></span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span></span><br><span class="line"><span class="title function_">main</span> <span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line"> {</span><br><span class="line"> <span class="built_in">fprintf</span> (<span class="built_in">stderr</span>, <span class="string">"starting up ...\n"</span>);</span><br><span class="line"> caml_startup (argv);</span><br><span class="line"> <span class="built_in">fprintf</span> (<span class="built_in">stderr</span>, <span class="string">"acquiring ...\n"</span>);</span><br><span class="line"> caml_acquire_runtime_system ();</span><br><span class="line"> <span class="built_in">fprintf</span> (<span class="built_in">stderr</span>, <span class="string">"acquired\n"</span>);</span><br><span class="line"> <span class="comment">// here is where I would be calling an OCaml callback</span></span><br><span class="line"> <span class="comment">// omitted for simplicity</span></span><br><span class="line"> caml_release_runtime_system ();</span><br><span class="line"> <span class="built_in">exit</span> (<span class="number">0</span>);</span><br><span class="line"> }</span><br></pre></td></tr></table></figure> - -<p>然后用OCaml5的ocaml native compiler编译一下(这里我用的是<code>ocaml-variants.5.0.0+options</code>):<br><code>ocamlopt -g test-ocaml-5.c test.ml -o test-ocaml-5</code></p> +<p>然后用OCaml5的ocaml native compiler编译一下(这里我用的是<code>ocaml-variants.5.0.0+options</code>):<br> +<code>ocamlopt -g test-ocaml-5.c test.ml -o test-ocaml-5</code></p> <p>运行<code>test-ocaml-5</code> 会出现:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">starting up ...</span><br><span class="line">hello from OCaml</span><br><span class="line">acquiring ...</span><br><span class="line">Fatal error: Fatal error during lock: Resource deadlock avoided</span><br><span class="line"></span><br><span class="line">[1] 8998 IOT instruction (core dumped) ./test-ocaml-5</span><br></pre></td></tr></table></figure> - -<p>这里我尝试了一下 4.14.0 和 4.14.1 , 都没有出现这个情况,而如果用<code>threads</code>编译的话:<br><code>ocamlopt -g -I +unix unix.cmxa -I +threads threads.cmxa test-ocaml-5.c test.ml -o test-ocaml-5</code></p> +<p>这里我尝试了一下 4.14.0 和 4.14.1 , 都没有出现这个情况,而如果用<code>threads</code>编译的话:<br> +<code>ocamlopt -g -I +unix unix.cmxa -I +threads threads.cmxa test-ocaml-5.c test.ml -o test-ocaml-5</code></p> <p>无论在5.0还是4.14.x,都会挂起。</p> <p>出现这个问题的一个可能原因是,在<code>test-ocaml-5.c</code>中,我在开头调用了<code>caml_startup()</code>,这会让当前线程获取锁,而<code>caml_acquire_runtime_system()</code>会再次获取它,<code>caml_acquire_runtime_system()</code> 应该在<code>caml_release_runtime_system()</code>之后调用:</p> <figure class="highlight ocaml"><table><tr><td class="code"><pre><span class="line"><span class="built_in">int</span></span><br><span class="line">main (<span class="built_in">int</span> argc, <span class="built_in">char</span> *argv<span class="literal">[]</span>)</span><br><span class="line"> {</span><br><span class="line"> fprintf (stderr, <span class="string">"starting up ...\n"</span>);</span><br><span class="line"> caml_startup (argv);</span><br><span class="line"> fprintf (stderr, <span class="string">"acquiring ...\n"</span>);</span><br><span class="line"> caml_release_runtime_system <span class="literal">()</span>;</span><br><span class="line"> caml_acquire_runtime_system <span class="literal">()</span>;</span><br><span class="line"> fprintf (stderr, <span class="string">"acquired\n"</span>);</span><br><span class="line"> exit (<span class="number">0</span>);</span><br><span class="line"> }</span><br></pre></td></tr></table></figure> - <p>运行结果为:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">starting up ...</span><br><span class="line">hello from OCaml</span><br><span class="line">acquiring ...</span><br><span class="line">acquired</span><br></pre></td></tr></table></figure>]]></content> <tags> @@ -2514,9 +2714,10 @@ await prisma.$transaction(async tx => { <url>/2025/07/08/dadgad/</url> <content><![CDATA[<p>模态定弦的空弦音不直接构成传统意义上的大调或小调和弦,而是形成一种听感上更为空灵、悬浮的“挂留和弦”(Suspended Chord)效果。</p> <p><strong>DADGAD (发音为 “dad-gad”):</strong> 这是凯尔特音乐(Celtic Music)中最具代表性的定弦。它的空弦音给人一种既非大调也非小调的模糊感,充满了神秘和悠远的色彩,非常适合营造氛围音乐和复杂的指弹旋律。</p> -<p>挂留和弦(Suspended Chord),通常简写为 <strong>“sus”<strong>,是一种在传统和弦结构上进行了巧妙“修改”的和弦。它的核心特点是:</strong>用一个非三度的音,去“替代”或“悬挂”了原本决定和弦大/小调色彩的三度音</strong>,从而创造出一种独特的声音效果。</p> +<p>挂留和弦(Suspended Chord),通常简写为 <strong>“sus”</strong>,是一种在传统和弦结构上进行了巧妙“修改”的和弦。它的核心特点是:<strong>用一个非三度的音,去“替代”或“悬挂”了原本决定和弦大/小调色彩的三度音</strong>,从而创造出一种独特的声音效果。</p> <p>想象一个标准的大三和弦或小三和弦,它由<strong>根音、三度音和五度音</strong>构成。其中,<strong>三度音</strong>是决定这个和弦听起来是明亮、开心的“大调”,还是忧郁、伤感的“小调”的关键。</p> -<p>而挂留和弦,就是把这个关键的“三度音”暂时拿掉,换上别的音。最常见的替代者有两个:<br>一是 <strong>纯四度音 (Perfect 4th)</strong> ,二是 <strong>大二度音 (Major 2nd)</strong> 。</p> +<p>而挂留和弦,就是把这个关键的“三度音”暂时拿掉,换上别的音。最常见的替代者有两个:<br> +一是 <strong>纯四度音 (Perfect 4th)</strong> ,二是 <strong>大二度音 (Major 2nd)</strong> 。</p> <p><strong>sus4 和弦 (挂四和弦)</strong> 由 <strong>根音 (1) + 纯四度音 (4) + 纯五度音 (5)</strong> 构成,即用<strong>四度音</strong>替代了原本的三度音。听感上,这是最常见的挂留和弦。它创造出一种<strong>强烈而悬浮的张力感</strong>,声音既不属于大调也不属于小调,听起来非常“开阔”。例如,一个 <strong>Csus4</strong> 和弦,就是由 C、F、G 三个音构成,取代了标准C大调和弦(C-E-G)中的 E 音。</p> <p><strong>sus2 和弦 (挂二和弦)</strong> 由 <strong>根音 (1) + 大二度音 (2) + 纯五度音 (5)</strong> 构成,特点是用二度音替代了原本的三度音。听感上,sus2和弦的声音比sus4更柔和、更明亮一些。它同样具有开放、模糊的色彩,但张力感稍弱,听起来更像是一种平静、梦幻的色彩和弦。例如,一个 <strong>Csus2</strong> 和弦,就是由 C、D、G 三个音构成,取代了标准C大调和弦(C-E-G)中的 E 音。</p> <p>而 DADGAD 定弦方式的空弦音,其核心就是一个挂留和弦,具体来说是一个 Dsus4 和弦。当你弹响 DADGAD 的所有空弦时,你实际上听到的就是 <strong>D、G、A</strong> 这三个音在不同八度上的叠加和共鸣。这三个音不多不少,正好构成了 <strong>Dsus4</strong> 和弦。</p> @@ -2530,41 +2731,44 @@ await prisma.$transaction(async tx => { <entry> <title>在临床医疗领域中的数据库外键设计取舍</title> <url>/2025/09/09/database-fk-design-in-clinical-medicine/</url> - <content><![CDATA[<p>从关系模型的理论视角看,外键作为参照完整性约束的实现机制,理论上能确保跨表数据的逻辑一致性,避免出现孤立记录(orphaned records)[^theoretical_consistency]。但在高并发、分布式、快速迭代的业务场景中,强制外键约束会引入显著的运行时开销:每次写操作都需要执行跨表的锁检查与索引查询,在 OLTP 系统中尤其影响吞吐量。以 TPC-C 基准测试为例,启用外键的订单创建事务延迟可能增加 15%-30%,因为数据库引擎必须验证客户表与订单项表的关联有效性,这在每秒数千次写入的场景下会成为锁竞争瓶颈[^tpc_c_performance]。</p> -<p>而在分库分表架构中,外键约束跨物理节点时的实现复杂度呈指数级上升——分布式事务的两阶段提交协议(2PC)不仅降低性能,还可能因网络分区导致事务悬挂,这与 CAP 定理中 “分布式系统无法同时满足一致性、可用性与分区容错性” 的根本限制直接冲突[^cap_theorem]。</p> -<p>互联网行业的大规模实践表明,当单表数据量超过千万级或需要水平扩展时,放弃外键往往成为必然选择[^distributed_systems]。</p> -<p>这种设计取舍背后还隐藏着更深层的工程哲学转变。传统单体架构中,数据库承担了业务规则的核心验证职责,而微服务与领域驱动设计(DDD)的兴起将数据一致性边界从存储层上移到应用层[^fowler_architecture]。例如在电商订单履约流程中,订单服务与库存服务的关联不再依赖数据库外键,而是通过 Saga 事务模式或事件溯源(Event Sourcing)机制实现最终一致性。</p> + <content><![CDATA[<p>从关系模型的理论视角看,外键作为参照完整性约束的实现机制,理论上能确保跨表数据的逻辑一致性,避免出现孤立记录(orphaned records)<sup class="footnote-ref"><a href="#fn1" id="fnref1">[1]</a></sup>。但在高并发、分布式、快速迭代的业务场景中,强制外键约束会引入显著的运行时开销:每次写操作都需要执行跨表的锁检查与索引查询,在 OLTP 系统中尤其影响吞吐量。以 TPC-C 基准测试为例,启用外键的订单创建事务延迟可能增加 15%-30%,因为数据库引擎必须验证客户表与订单项表的关联有效性,这在每秒数千次写入的场景下会成为锁竞争瓶颈<sup class="footnote-ref"><a href="#fn2" id="fnref2">[2]</a></sup>。</p> +<p>而在分库分表架构中,外键约束跨物理节点时的实现复杂度呈指数级上升——分布式事务的两阶段提交协议(2PC)不仅降低性能,还可能因网络分区导致事务悬挂,这与 CAP 定理中 “分布式系统无法同时满足一致性、可用性与分区容错性” 的根本限制直接冲突<sup class="footnote-ref"><a href="#fn3" id="fnref3">[3]</a></sup>。</p> +<p>互联网行业的大规模实践表明,当单表数据量超过千万级或需要水平扩展时,放弃外键往往成为必然选择<sup class="footnote-ref"><a href="#fn4" id="fnref4">[4]</a></sup>。</p> +<p>这种设计取舍背后还隐藏着更深层的工程哲学转变。传统单体架构中,数据库承担了业务规则的核心验证职责,而微服务与领域驱动设计(DDD)的兴起将数据一致性边界从存储层上移到应用层<sup class="footnote-ref"><a href="#fn5" id="fnref5">[5]</a></sup>。例如在电商订单履约流程中,订单服务与库存服务的关联不再依赖数据库外键,而是通过 Saga 事务模式或事件溯源(Event Sourcing)机制实现最终一致性。</p> <p>应用层通过领域事件(如 OrderCreated 事件)触发库存预占操作,并在消息队列保障下实现跨服务协调。这种方式虽然增加了业务代码的复杂度,但换取了服务解耦与独立部署能力, 即, 当库存服务需要重构时,无需协调订单服务的数据库变更,这大大提升了敏捷开发效率。</p> -<p>阿里的《企业级分布式应用架构》中表示, 其核心交易系统在数据库层面移除外键后,需求迭代周期缩短40%,因为团队不再受制于跨服务的数据库变更审批流程[^alibaba_architecture]。</p> +<p>阿里的《企业级分布式应用架构》中表示, 其核心交易系统在数据库层面移除外键后,需求迭代周期缩短40%,因为团队不再受制于跨服务的数据库变更审批流程<sup class="footnote-ref"><a href="#fn6" id="fnref6">[6]</a></sup>。</p> <p>然而放弃外键绝非没有代价。</p> -<p>最直接的影响是数据一致性的保障责任从 DBA 转移至应用开发团队,当业务逻辑存在缺陷时,极易产生逻辑断裂的数据,例如支付成功但订单状态未更新的场景[^data_integrity_issues]。这类问题往往在特定异常路径下才暴露,调试难度远高于数据库层面的即时约束报错。</p> -<p>对于历史数据迁移和数据分析,缺乏外键约束的模型在构建数仓时,ETL 过程必须额外实现参照验证逻辑,否则维度表与事实表的断裂关联会导致分析结论失真。Netflix 在其技术博客中披露,早期用户观看记录与内容元数据的关联缺失曾导致推荐模型准确率下降 7%,最终通过构建独立的数据校验服务补救[^data_warehouse_challenges]。</p> +<p>最直接的影响是数据一致性的保障责任从 DBA 转移至应用开发团队,当业务逻辑存在缺陷时,极易产生逻辑断裂的数据,例如支付成功但订单状态未更新的场景<sup class="footnote-ref"><a href="#fn7" id="fnref7">[7]</a></sup>。这类问题往往在特定异常路径下才暴露,调试难度远高于数据库层面的即时约束报错。</p> +<p>对于历史数据迁移和数据分析,缺乏外键约束的模型在构建数仓时,ETL 过程必须额外实现参照验证逻辑,否则维度表与事实表的断裂关联会导致分析结论失真。Netflix 在其技术博客中披露,早期用户观看记录与内容元数据的关联缺失曾导致推荐模型准确率下降 7%,最终通过构建独立的数据校验服务补救<sup class="footnote-ref"><a href="#fn8" id="fnref8">[8]</a></sup>。</p> <blockquote> <p>真正专业的架构决策需要基于量化指标进行场景化评估。</p> </blockquote> <p>对于交易系统等强一致性场景,普遍建议仅在单数据库实例内保留关键外键(如订单与订单项的关联),而跨服务关系则采用异步校验;</p> -<p>对于分析型系统或写入吞吐要求极高的场景(如IoT设备数据采集),可完全放弃外键,但必须配套实施三大保障措施:一是在应用层实现幂等写入与版本控制(如使用乐观锁的CAS操作),二是部署定时数据稽核任务(如每日扫描账户余额负值等异常状态),三是通过变更数据捕获(CDC)技术将操作日志实时写入审计表[^engineering_guidelines]。</p> +<p>对于分析型系统或写入吞吐要求极高的场景(如IoT设备数据采集),可完全放弃外键,但必须配套实施三大保障措施:一是在应用层实现幂等写入与版本控制(如使用乐观锁的CAS操作),二是部署定时数据稽核任务(如每日扫描账户余额负值等异常状态),三是通过变更数据捕获(CDC)技术将操作日志实时写入审计表<sup class="footnote-ref"><a href="#fn9" id="fnref9">[9]</a></sup>。</p> <blockquote> -<p>现代云数据库如 Amazon Aurora 已提供逻辑外键(logical foreign keys)的折中方案:它不强制运行时约束,但通过存储过程与触发器记录关联规则,在数据导出或特定查询时触发验证,这在保持写性能的同时保留了部分数据治理能力[^aurora_logical_foreign_keys]。</p> +<p>现代云数据库如 Amazon Aurora 已提供逻辑外键(logical foreign keys)的折中方案:它不强制运行时约束,但通过存储过程与触发器记录关联规则,在数据导出或特定查询时触发验证,这在保持写性能的同时保留了部分数据治理能力<sup class="footnote-ref"><a href="#fn10" id="fnref10">[10]</a></sup>。</p> </blockquote> <p>所以最终判断是否使用外键应基于四个维度的具体测量:</p> -<p>一、业务容忍的数据不一致窗口(如金融系统要求秒级,内容推荐可接受小时级)。<br>二、峰值QPS与事务复杂度。<br>三、团队对分布式一致性的掌控能力。<br>四、监控修复工具链的完备性。</p> +<p>一、业务容忍的数据不一致窗口(如金融系统要求秒级,内容推荐可接受小时级)。<br> +二、峰值QPS与事务复杂度。<br> +三、团队对分布式一致性的掌控能力。<br> +四、监控修复工具链的完备性。</p> <blockquote> <p>当系统处于初创期时保留外键可降低认知负担,但进入高速增长期后需有计划地将约束责任前移至应用层。</p> </blockquote> -<p>在临床医疗领域的药物研发项目与慢病管理系统中,数据库外键的取舍决策必须超越传统性能权衡,这是因为医疗数据承担着生命安全关联性、法规强制性约束与临床逻辑不可妥协性这些特殊情况[^medical_data_criticality]。</p> +<p>在临床医疗领域的药物研发项目与慢病管理系统中,数据库外键的取舍决策必须超越传统性能权衡,这是因为医疗数据承担着生命安全关联性、法规强制性约束与临床逻辑不可妥协性这些特殊情况<sup class="footnote-ref"><a href="#fn11" id="fnref11">[11]</a></sup>。</p> <p>这类系统的核心矛盾在于:医疗数据的完整性缺陷可能直接导致误诊、用药错误甚至患者死亡,而过度依赖外键又可能阻碍紧急场景下的操作敏捷性(如 ICU 实时数据录入)。因此,外键策略需分层设计,依据数据域的风险等级与业务场景动态调整。</p> -<p>以药物研发项目数据库为例,其数据模型涉及化合物结构、临床试验阶段、受试者信息及不良事件报告等强依赖实体。在 I 期临床试验阶段(单中心小规模数据),保留外键是合规刚需:当录入受试者用药事件时,必须强制关联有效的伦理委员会批准编号(protocol_id)和药品批号(lot_number)。这并非仅出于数据规范性,FDA 21 CFR Part 11 明确规定电子记录需具备 “可靠的归属关系”,若不良事件记录无法追溯到具体药物批次,将导致整个试验数据被判定为无效[^fda_regulations]。</p> -<p>实测数据显示,在 PostgreSQL 中启用外键约束后,单次药物不良反应事件录入延迟仅增加0.8ms(从3.2ms到4.0ms),但可100%拦截”批号不存在”类错误。这类错误在无外键环境下平均占人工稽查量的 37%(基于 Pfizer 2022 年临床数据质量报告),其修正成本是预防成本的22倍[^pfa_data_quality]。因此,在核心试验元数据层(研究方案、受试者登记表),外键应作为技术强制项而非可选项。</p> +<p>以药物研发项目数据库为例,其数据模型涉及化合物结构、临床试验阶段、受试者信息及不良事件报告等强依赖实体。在 I 期临床试验阶段(单中心小规模数据),保留外键是合规刚需:当录入受试者用药事件时,必须强制关联有效的伦理委员会批准编号(protocol_id)和药品批号(lot_number)。这并非仅出于数据规范性,FDA 21 CFR Part 11 明确规定电子记录需具备 “可靠的归属关系”,若不良事件记录无法追溯到具体药物批次,将导致整个试验数据被判定为无效<sup class="footnote-ref"><a href="#fn12" id="fnref12">[12]</a></sup>。</p> +<p>实测数据显示,在 PostgreSQL 中启用外键约束后,单次药物不良反应事件录入延迟仅增加0.8ms(从3.2ms到4.0ms),但可100%拦截"批号不存在"类错误。这类错误在无外键环境下平均占人工稽查量的 37%(基于 Pfizer 2022 年临床数据质量报告),其修正成本是预防成本的22倍<sup class="footnote-ref"><a href="#fn13" id="fnref13">[13]</a></sup>。因此,在核心试验元数据层(研究方案、受试者登记表),外键应作为技术强制项而非可选项。</p> <p>然而当进入 III 期多中心试验阶段,分布式数据采集就会出现问题,某中心可能临时使用本地 SQLite 数据库录入紧急病例,此时跨地域外键校验会因网络延迟导致生命体征数据积压。</p> <p>此处的取舍在于 “约束分级”:对患者身份标识符(如随机化编号)等关键关系保留外键,而对非致命性关联(如患者地址分类码)改用应用层校验。</p> -<p>更前沿的实践是采用基于 FHIR(Fast Healthcare Interoperability Resources)标准的松散耦合架构——当录入不良事件时,系统不强制外键,但通过 HL7 FHIR 的 Reference 机制调用中央受试者服务的实时验证 API。这既满足了 EudraCT(欧盟临床试验数据库)要求的”数据关联可追溯性”,又避免了传统外键的分布式锁竞争[^fhir_standard]。默克药厂的临床数据管理平台实测表明,该方案将跨中心数据整合延迟降低 63%,同时通过 OAuth 2.0 保障验证请求的原子性。</p> +<p>更前沿的实践是采用基于 FHIR(Fast Healthcare Interoperability Resources)标准的松散耦合架构——当录入不良事件时,系统不强制外键,但通过 HL7 FHIR 的 Reference 机制调用中央受试者服务的实时验证 API。这既满足了 EudraCT(欧盟临床试验数据库)要求的"数据关联可追溯性",又避免了传统外键的分布式锁竞争<sup class="footnote-ref"><a href="#fn14" id="fnref14">[14]</a></sup>。默克药厂的临床数据管理平台实测表明,该方案将跨中心数据整合延迟降低 63%,同时通过 OAuth 2.0 保障验证请求的原子性。</p> <hr> <p>慢病管理系统的决策逻辑更为精细。以糖尿病患者管理系统为例,血糖监测记录表(blood_glucose_readings)与患者档案表(patient_profiles)的关联存在三种典型场景:</p> <ul> -<li><strong>预防性场景</strong>(门诊定期随访):外键应强制存在。每次录入糖化血红蛋白值必须关联有效患者ID,否则会导致个性化治疗方案生成错误。英国 NHS 的实践证明,启用外键后糖尿病并发症误判率下降 21%,因为系统不再出现 “记录归属未知患者” 的脏数据[^nhs_data_quality]。</li> -<li><strong>应急场景</strong>(急救车实时数据传输):需临时禁用外键。当急救人员通过移动设备录入昏迷患者的血糖值时,若因患者 ID 验证失败导致写入中断,将危及生命。此时系统应将数据写入隔离缓冲区(quarantine zone),外键校验延迟至网络恢复后由后台服务补做。这种设计已进入 ISO/TR 20514 医疗设备通信规范[^iso_medical_standard]。</li> -<li><strong>分析场景</strong>(长期队列研究):采用逻辑外键替代物理外键。研究型数据库中,患者 ID 仅作为业务键存在,可以通过 Apache Atlas 等数据治理工具构建血缘关系图谱,在 ETL 过程中自动执行完整性检查。约翰霍普金斯大学的慢病研究平台显示,该方式在保持数据挖掘效率的同时,将人工数据清洗工时减少 58%[^data_governance_tools]。</li> +<li><strong>预防性场景</strong>(门诊定期随访):外键应强制存在。每次录入糖化血红蛋白值必须关联有效患者ID,否则会导致个性化治疗方案生成错误。英国 NHS 的实践证明,启用外键后糖尿病并发症误判率下降 21%,因为系统不再出现 “记录归属未知患者” 的脏数据<sup class="footnote-ref"><a href="#fn15" id="fnref15">[15]</a></sup>。</li> +<li><strong>应急场景</strong>(急救车实时数据传输):需临时禁用外键。当急救人员通过移动设备录入昏迷患者的血糖值时,若因患者 ID 验证失败导致写入中断,将危及生命。此时系统应将数据写入隔离缓冲区(quarantine zone),外键校验延迟至网络恢复后由后台服务补做。这种设计已进入 ISO/TR 20514 医疗设备通信规范<sup class="footnote-ref"><a href="#fn16" id="fnref16">[16]</a></sup>。</li> +<li><strong>分析场景</strong>(长期队列研究):采用逻辑外键替代物理外键。研究型数据库中,患者 ID 仅作为业务键存在,可以通过 Apache Atlas 等数据治理工具构建血缘关系图谱,在 ETL 过程中自动执行完整性检查。约翰霍普金斯大学的慢病研究平台显示,该方式在保持数据挖掘效率的同时,将人工数据清洗工时减少 58%<sup class="footnote-ref"><a href="#fn17" id="fnref17">[17]</a></sup>。</li> </ul> <p>对于法规与安全维度。HIPAA 要求所有患者数据关联必须可审计,而 GDPR “被遗忘权” 又要求能彻底解耦数据。若使用传统 ON DELETE CASCADE 外键,删除患者记录会级联抹除所有医疗历史,违反 FDA 要求的 “试验数据永久保留” 原则。</p> <p>一个可行的方案是设计<strong>策略性外键</strong>:</p> @@ -2573,12 +2777,55 @@ await prisma.$transaction(async tx => { <li>关键表(如用药记录)不设置 ON DELETE 动作,改用逻辑删除标记(<code>is_active BOOLEAN</code>)</li> <li>当触发患者数据删除请求时,外键约束转换为业务规则检查——确保研究数据经脱敏后转入归档库(符合 21 CFR 11.10(e))</li> </ol> -<p>这种设计在 Mayo Clinic 的慢病管理系统中得到验证:既满足每秒 300 次的生命体征写入吞吐(外键校验异步化至Kafka流处理),又通过区块链存证保留所有关联操作的审计轨迹[^mayo_clinic_case_study]。</p> +<p>这种设计在 Mayo Clinic 的慢病管理系统中得到验证:既满足每秒 300 次的生命体征写入吞吐(外键校验异步化至Kafka流处理),又通过区块链存证保留所有关联操作的审计轨迹<sup class="footnote-ref"><a href="#fn18" id="fnref18">[18]</a></sup>。</p> <blockquote> <p>核心原则是:<strong>外键的存在与否取决于业务操作的后果严重性,而非单纯的技术指标</strong>。当数据断裂可能直接伤害患者时,必须用外键,当系统响应速度关乎生命时,则需设计更智能的补偿机制。</p> </blockquote> -<p>不过现代云医疗数据库(如AWS HealthLake)已内置此类混合策略:在 OLTP 层保留关键外键,同时提供 FHIR 资源引用的逻辑一致性检查[^aws_healthlake]。开发者可以定期通过 Chaos Engineering 测试数据断裂场景,模拟删除患者记录后检查系统恢复能力。</p> -<h2 id="参考文献:"><a href="#参考文献:" class="headerlink" title="参考文献:"></a>参考文献:</h2><p>[^theoretical_consistency]: Gray, J., & Reuter, A. (1993). Transaction Processing: Concepts and Techniques. Morgan Kaufmann.<br>[^tpc_c_performance]: CockroachDB 团队性能基准测试报告 (2020-2022)<br>[^cap_theorem]: Taft, R., et al. (2020). CockroachDB: The Resilient Geo-Distributed SQL Database. SIGMOD.<br>[^distributed_systems]: Google Cloud Architecture Center. (2022). Designing for Consistency in Distributed Databases.<br>[^fowler_architecture]: Fowler, M. (2003). Patterns of Enterprise Application Architecture. Addison-Wesley.<br>[^alibaba_architecture]: Alibaba Group. (2019). Nacos: A Dynamic Naming and Configuration Service for Cloud Native Applications.<br>[^data_integrity_issues]: Kleppmann, M. (2017). Designing Data-Intensive Applications. O’Reilly.<br>[^data_warehouse_challenges]: Netflix Technology Blog (2018). “When Data Relationships Break: Lessons from Recommendation Systems”<br>[^engineering_guidelines]: Kleppmann, M. (2020). Transaction Processing in Healthcare Systems. Communications of the ACM, 63(7).<br>[^aurora_logical_foreign_keys]: AWS Database Blog. (2021). Logical foreign keys in Amazon Aurora.<br>[^medical_data_criticality]: Jensen, P. B., et al. (2019). Mining Electronic Health Records: Towards Better Research Applications and Clinical Care. Nature Reviews Genetics.<br>[^fda_regulations]: U.S. Food and Drug Administration. (2023). 21 CFR Part 11: Electronic Records; Electronic Signatures.<br>[^pfa_data_quality]: Pfizer Clinical Data Science Team. (2022). Annual Data Quality Report. Internal Publication.<br>[^fhir_standard]: HL7 International. (2022). FHIR R4 Clinical Reasoning Module.<br>[^nhs_data_quality]: NHS Digital. (2022). Data Quality Framework for Healthcare Systems.<br>[^iso_medical_standard]: ISO/TR 20514:2021. Health informatics — Framework for integrity of health information.<br>[^data_governance_tools]: Johns Hopkins Medical Center Technical Report (2022). Data Governance in Chronic Disease Research.<br>[^mayo_clinic_case_study]: Mayo Clinic Proceedings. (2021). Design Patterns for Resilient Chronic Disease Management Systems. 96(8).<br>[^aws_healthlake]: AWS. (2023). HealthLake Security and Compliance Controls.</p> +<p>不过现代云医疗数据库(如AWS HealthLake)已内置此类混合策略:在 OLTP 层保留关键外键,同时提供 FHIR 资源引用的逻辑一致性检查<sup class="footnote-ref"><a href="#fn19" id="fnref19">[19]</a></sup>。开发者可以定期通过 Chaos Engineering 测试数据断裂场景,模拟删除患者记录后检查系统恢复能力。</p> +<h2 id="参考文献:"><a class="header-anchor" href="#参考文献:">¶</a>参考文献:</h2> +<hr class="footnotes-sep"> +<section class="footnotes"> +<ol class="footnotes-list"> +<li id="fn1" class="footnote-item"><p>Gray, J., & Reuter, A. (1993). Transaction Processing: Concepts and Techniques. Morgan Kaufmann. <a href="#fnref1" class="footnote-backref">↩︎</a></p> +</li> +<li id="fn2" class="footnote-item"><p>CockroachDB 团队性能基准测试报告 (2020-2022) <a href="#fnref2" class="footnote-backref">↩︎</a></p> +</li> +<li id="fn3" class="footnote-item"><p>Taft, R., et al. (2020). CockroachDB: The Resilient Geo-Distributed SQL Database. SIGMOD. <a href="#fnref3" class="footnote-backref">↩︎</a></p> +</li> +<li id="fn4" class="footnote-item"><p>Google Cloud Architecture Center. (2022). Designing for Consistency in Distributed Databases. <a href="#fnref4" class="footnote-backref">↩︎</a></p> +</li> +<li id="fn5" class="footnote-item"><p>Fowler, M. (2003). Patterns of Enterprise Application Architecture. Addison-Wesley. <a href="#fnref5" class="footnote-backref">↩︎</a></p> +</li> +<li id="fn6" class="footnote-item"><p>Alibaba Group. (2019). Nacos: A Dynamic Naming and Configuration Service for Cloud Native Applications. <a href="#fnref6" class="footnote-backref">↩︎</a></p> +</li> +<li id="fn7" class="footnote-item"><p>Kleppmann, M. (2017). Designing Data-Intensive Applications. O’Reilly. <a href="#fnref7" class="footnote-backref">↩︎</a></p> +</li> +<li id="fn8" class="footnote-item"><p>Netflix Technology Blog (2018). “When Data Relationships Break: Lessons from Recommendation Systems” <a href="#fnref8" class="footnote-backref">↩︎</a></p> +</li> +<li id="fn9" class="footnote-item"><p>Kleppmann, M. (2020). Transaction Processing in Healthcare Systems. Communications of the ACM, 63(7). <a href="#fnref9" class="footnote-backref">↩︎</a></p> +</li> +<li id="fn10" class="footnote-item"><p>AWS Database Blog. (2021). Logical foreign keys in Amazon Aurora. <a href="#fnref10" class="footnote-backref">↩︎</a></p> +</li> +<li id="fn11" class="footnote-item"><p>Jensen, P. B., et al. (2019). Mining Electronic Health Records: Towards Better Research Applications and Clinical Care. Nature Reviews Genetics. <a href="#fnref11" class="footnote-backref">↩︎</a></p> +</li> +<li id="fn12" class="footnote-item"><p>U.S. Food and Drug Administration. (2023). 21 CFR Part 11: Electronic Records; Electronic Signatures. <a href="#fnref12" class="footnote-backref">↩︎</a></p> +</li> +<li id="fn13" class="footnote-item"><p>Pfizer Clinical Data Science Team. (2022). Annual Data Quality Report. Internal Publication. <a href="#fnref13" class="footnote-backref">↩︎</a></p> +</li> +<li id="fn14" class="footnote-item"><p>HL7 International. (2022). FHIR R4 Clinical Reasoning Module. <a href="#fnref14" class="footnote-backref">↩︎</a></p> +</li> +<li id="fn15" class="footnote-item"><p>NHS Digital. (2022). Data Quality Framework for Healthcare Systems. <a href="#fnref15" class="footnote-backref">↩︎</a></p> +</li> +<li id="fn16" class="footnote-item"><p>ISO/TR 20514:2021. Health informatics — Framework for integrity of health information. <a href="#fnref16" class="footnote-backref">↩︎</a></p> +</li> +<li id="fn17" class="footnote-item"><p>Johns Hopkins Medical Center Technical Report (2022). Data Governance in Chronic Disease Research. <a href="#fnref17" class="footnote-backref">↩︎</a></p> +</li> +<li id="fn18" class="footnote-item"><p>Mayo Clinic Proceedings. (2021). Design Patterns for Resilient Chronic Disease Management Systems. 96(8). <a href="#fnref18" class="footnote-backref">↩︎</a></p> +</li> +<li id="fn19" class="footnote-item"><p>AWS. (2023). HealthLake Security and Compliance Controls. <a href="#fnref19" class="footnote-backref">↩︎</a></p> +</li> +</ol> +</section> ]]></content> <tags> <tag>Technique</tag> @@ -2588,11 +2835,12 @@ await prisma.$transaction(async tx => { <entry> <title>由甲醛开始的碎碎念</title> <url>/2025/07/11/fuck-hcho/</url> - <content><![CDATA[<p>前几天和群友聊到甲醛相关的东东,有点好奇甲醛进入人体之后的一系列反应,于逝,<del>我去吸了两口</del> ,先来看看一些无聊的总结:</p> + <content><![CDATA[<p>前几天和群友聊到甲醛相关的东东,有点好奇甲醛进入人体之后的一系列反应,于逝,<s>我去吸了两口</s> ,先来看看一些无聊的总结:</p> <p>吸入甲醛后,人体之所以会产生眼部灼痛、喉咙刺痒、呼吸困难等一系列强烈的不适感,是因为甲醛作为一种高活性、强刺激性的化学物质,对我们的身体构成了从宏观到微观的多层次、多途径的直接攻击。其影响方式主要可以归结为两大方面:<strong>直接的刺激与腐蚀作用</strong>和<strong>深层的细胞毒性与遗传毒性</strong>。</p> <p>当甲醛气体通过呼吸进入人体,首当其冲的是我们的眼睛和呼吸道黏膜。这些部位的细胞直接暴露在甲醛的攻击下,引发一系列即时且强烈的不适症状:</p> <ul> -<li><strong>对黏膜的强烈刺激:</strong> 甲醛具有极强的亲水性和反应活性,能迅速与眼睛结膜、鼻腔、咽喉和气管等部位黏膜表面的蛋白质和水分发生反应。这种反应会直接损伤黏膜组织,导致神经末梢受到强烈刺激。<ul> +<li><strong>对黏膜的强烈刺激:</strong> 甲醛具有极强的亲水性和反应活性,能迅速与眼睛结膜、鼻腔、咽喉和气管等部位黏膜表面的蛋白质和水分发生反应。这种反应会直接损伤黏膜组织,导致神经末梢受到强烈刺激。 +<ul> <li><strong>眼部症状:</strong> 眼睛会感到灼烧、刺痛、发痒和不自主流泪。</li> <li><strong>呼吸道症状:</strong> 喉咙会感到干燥、刺痛、咳嗽,高浓度下更会引发胸闷、气喘,甚至喉头水肿和肺水肿,导致呼吸极度困难。</li> </ul> @@ -2603,66 +2851,82 @@ await prisma.$transaction(async tx => { <ul> <li><strong>蛋白质变性:</strong> 甲醛能够与构成生命基础的蛋白质中的氨基(-NH2)发生反应,形成“亚甲基桥”,破坏蛋白质原有的三维结构,使其失去正常的生理功能。细胞的功能依赖于各种蛋白质(酶、结构蛋白等)的正常工作,蛋白质变性意味着细胞代谢紊乱、功能障碍,甚至死亡。这在本质上是一种“腐蚀”作用,也是福尔马林(甲醛水溶液)能用作防腐剂的根本原因。</li> <li><strong>诱导细胞凋亡与氧化应激:</strong> 研究表明,甲醛会损伤细胞内的能量工厂——线粒体,诱导细胞产生大量的活性氧(ROS)。过量的活性氧会破坏细胞膜、蛋白质和DNA,引发“氧化应激”反应,并最终启动细胞的程序性死亡(凋亡)机制。</li> -<li><strong>遗传毒性与致癌性:</strong> 甲醛最具危害性的影响在于其遗传毒性。它可以穿过细胞核,与遗传物质DNA和组蛋白(包裹DNA的蛋白质)形成“加合物”,这会干扰DNA的正常复制和修复过程,导致基因突变。<ul> +<li><strong>遗传毒性与致癌性:</strong> 甲醛最具危害性的影响在于其遗传毒性。它可以穿过细胞核,与遗传物质DNA和组蛋白(包裹DNA的蛋白质)形成“加合物”,这会干扰DNA的正常复制和修复过程,导致基因突变。 +<ul> <li><strong>致癌风险:</strong> 当这种基因损伤发生在关键的癌基因或抑癌基因上,并且人体的修复机制无法有效清除时,就可能导致细胞的异常增殖,最终引发癌症。世界卫生组织(WHO)下属的国际癌症研究机构(IARC)已将甲醛列为<strong>一类致癌物</strong>,有充分证据表明其与鼻咽癌、白血病等恶性肿瘤的发生密切相关。</li> </ul> </li> <li><strong>神经与免疫毒性:</strong> 甲醛还能对中枢神经系统产生毒性作用,导致头晕、头痛、记忆力减退、失眠等症状。同时,它也可能干扰免疫系统的正常功能,使人更容易过敏(如引发过敏性皮炎、哮喘)或抵抗力下降。</li> </ul> <hr> -<h2 id="甲醛与粘膜表面的蛋白质和水分发生反应?"><a href="#甲醛与粘膜表面的蛋白质和水分发生反应?" class="headerlink" title="甲醛与粘膜表面的蛋白质和水分发生反应?"></a>甲醛与粘膜表面的蛋白质和水分发生反应?</h2><p>当甲醛(HCHO)这个小而活泼的分子,遇到我们湿润的眼睛、鼻腔和喉咙黏膜时,它首先会迅速溶于黏膜表面的水分,形成甲二醇 (CH₂(OH)₂) 。这个形态的甲醛会将目标转向 <strong>蛋白质</strong>。</p> +<h2 id="甲醛与粘膜表面的蛋白质和水分发生反应?"><a class="header-anchor" href="#甲醛与粘膜表面的蛋白质和水分发生反应?">¶</a>甲醛与粘膜表面的蛋白质和水分发生反应?</h2> +<p>当甲醛(HCHO)这个小而活泼的分子,遇到我们湿润的眼睛、鼻腔和喉咙黏膜时,它首先会迅速溶于黏膜表面的水分,形成甲二醇 (CH₂(OH)₂) 。这个形态的甲醛会将目标转向 <strong>蛋白质</strong>。</p> <p>这个反应并非简单的接触,而是一种被称为“交联反应”(Cross-linking)的化学过程。具体来说:甲醛分子会精准地找到蛋白质分子链上的氨基(-NH₂),这是许多氨基酸的共同特征。接着与蛋白质的氨基发生反应,形成一个不稳定的中间体。这个中间体可以进一步与邻近的另一个蛋白质的氨基反应,从而在两个原本独立的蛋白质(或同一个蛋白质的不同部分)之间,强行架起一座“亚甲基桥”(-CH₂-)。</p> <p>蛋白质就像一团经过精确折叠、有着特定三维结构的精密机器,它的功能完全依赖于这个构型。而甲醛的“交联”反应,就像是往这台精密机器的各个活动关节之间,甚至和旁边的机器之间倒 502,给它们粘死了。</p> -<h3 id="为什么甲醛分子能精准地找到蛋白质分子链上的氨基?"><a href="#为什么甲醛分子能精准地找到蛋白质分子链上的氨基?" class="headerlink" title="为什么甲醛分子能精准地找到蛋白质分子链上的氨基?"></a>为什么甲醛分子能精准地找到蛋白质分子链上的氨基?</h3><p>“精准”这两个字,听起来像是一个有思想、有目标的动作,但实际上是一场由分子结构和电荷分布主导的化学反应。</p> -<p>甲醛分子(HCHO)的核心是一个<strong>羰基(C=O)</strong>。在这个结构中,氧原子(O)是一个电负性非常强的元素,它对电子有着极强的吸引力。它会大力地将碳氧双键中的共用电子云拉向自己。这种电子云的偏移,导致了与它相连的碳原子(C)周围的电子变得非常稀薄,从而带上了部分正电荷(δ+)。</p> +<h3 id="为什么甲醛分子能精准地找到蛋白质分子链上的氨基?"><a class="header-anchor" href="#为什么甲醛分子能精准地找到蛋白质分子链上的氨基?">¶</a>为什么甲醛分子能精准地找到蛋白质分子链上的氨基?</h3> +<p>“精准”这两个字,听起来像是一个有思想、有目标的动作,但实际上是一场由分子结构和电荷分布主导的化学反应。</p> +<p>甲醛分子(HCHO)的核心是一个<strong>羰基(C=O)</strong>。在这个结构中,氧原子(O)是一个电负性非常强的元素,它对电子有着极强的吸引力。它会大力地将碳氧双键中的共用电子云拉向自己。这种电子云的偏移,导致了与它相连的碳原子(C)周围的电子变得非常稀薄,从而带上了部分正电荷(δ+)。</p> <p>在化学上,这样一个“缺少电子”、对电子充满渴望的原子或基团,被称为“亲电体”(Electrophile)。</p> <p>氨基(-NH₂)在蛋白质中广泛存在,尤其是在赖氨酸、精氨酸等氨基酸的侧链上。氨基的核心是氮原子(N)。根据它的电子排布,氮原子的最外层有一对没有参与形成化学键的电子,这叫做 “孤对电子”(Lone Pair Electrons)。 这对孤对电子,使得氮原子成了一个电子云密度很高的区域,带上了<strong>部分负电荷(δ-)</strong>。</p> <p>这样一个拥有“富余”电子、并愿意用它去攻击其他正电中心的原子或基团,在化学上被称为 “亲核体”(Nucleophile)。</p> <p>当甲醛分子靠近蛋白质时,甲醛分子上带部分正电荷的碳原子(亲电体),与蛋白质氨基上带部分负电荷的氮原子(亲核体),会因基本的静电引力而相互靠近。一旦距离足够近,氨基上慷慨的“孤对电子”会毫不犹豫地“攻击”甲醛上那个渴望电子的碳原子,并与它形成一个新的化学键。</p> <p>这个过程,就是化学中的“亲核加成反应”。</p> -<h3 id="这个反应为何会损伤黏膜组织?"><a href="#这个反应为何会损伤黏膜组织?" class="headerlink" title="这个反应为何会损伤黏膜组织?"></a>这个反应为何会损伤黏膜组织?</h3><p>蛋白质被甲醛“交联” 这个过程在化学上称为 “蛋白质变性”,它直接导致了组织损伤。</p> +<h3 id="这个反应为何会损伤黏膜组织?"><a class="header-anchor" href="#这个反应为何会损伤黏膜组织?">¶</a>这个反应为何会损伤黏膜组织?</h3> +<p>蛋白质被甲醛“交联” 这个过程在化学上称为 “蛋白质变性”,它直接导致了组织损伤。</p> <p>首先黏膜细胞需要各种酶(本身也是蛋白质)来维持新陈代谢。被交联后,这些酶的结构被破坏,失去了活性,细胞的正常生理活动瞬间停滞。而细胞的骨架、细胞膜上的离子通道等结构蛋白,同样会被交联破坏。这导致细胞失去原有的形态,细胞膜的通透性被改变,甚至直接破裂。当大量的细胞功能瘫痪、结构崩解后,它们会迅速走向死亡。成片的细胞死亡,就意味着我们宏观可见的<strong>组织损伤</strong>。这本质上是一种<strong>微观的化学性灼伤</strong>。</p> <p>这也是为什么福尔马林(甲醛水溶液)能用来制作标本——它通过“交联”反应,将生物组织的所有蛋白质“固化”,使其永不腐败,但这对于活体组织而言,就是彻头彻尾的毁灭。</p> -<h3 id="为何神经末梢会受到强烈刺激?"><a href="#为何神经末梢会受到强烈刺激?" class="headerlink" title="为何神经末梢会受到强烈刺激?"></a>为何神经末梢会受到强烈刺激?</h3><p>我们的黏膜组织下,密布着丰富的神经末梢。</p> +<h3 id="为何神经末梢会受到强烈刺激?"><a class="header-anchor" href="#为何神经末梢会受到强烈刺激?">¶</a>为何神经末梢会受到强烈刺激?</h3> +<p>我们的黏膜组织下,密布着丰富的神经末梢。</p> <p>完好的黏膜上皮细胞是神经末梢的保护层。当这层保护被甲醛破坏,下方的神经末梢就直接暴露了出来。此时,高活性的甲醛分子可以直接攻击这些裸露的神经末梢,就像用化学品直接触碰神经一样,瞬间产生剧烈的刺激信号。</p> <p>被损伤和死亡的细胞,在“弥留之际”会释放出大量的化学信号物质,如前列腺素、缓激肽、组胺等。这些物质被称为“炎症介质”。而这些炎症介质本身,就是神经末梢上痛觉感受器的强效激活剂。它们会放大并持续地刺激神经,导致灼痛、瘙痒和刺痛感。</p> -<h3 id="什么是活性氧?"><a href="#什么是活性氧?" class="headerlink" title="什么是活性氧?"></a>什么是活性氧?</h3><p><strong>活性氧(Reactive Oxygen Species, ROS)</strong> 是一类含氧的、化学性质极其活泼的分子或自由基的总称。常见的活性氧有 超氧阴离子(O₂⁻•)、羟自由基(•OH)、过氧化氢(H₂O₂)等。它们的特点之一是其都带有“未配对的电子”,这使得它们在化学上极不稳定,迫切地想要从其他分子那里“抢夺”电子来让自己稳定下来。</p> -<p> 在正常情况下,我们身体会产生少量活性氧。它们是重要的信号分子,参与调节细胞生长、分化,并且是免疫细胞(如巨噬细胞)用来消灭入侵病原体(细菌、病毒)的“化学武器”。</p> -<p> 一旦活性氧的产生<strong>远远超过</strong>了细胞自身的清除能力(细胞内有超氧化物歧化酶SOD等“警察”来控制它们),就会形成“<strong>氧化应激</strong>”(Oxidative Stress)状态。这些失控的“小流氓”就会在细胞内肆意破坏,攻击一切它们遇到的分子。</p> -<h3 id="甲醛如何诱导线粒体产生大量活性氧?"><a href="#甲醛如何诱导线粒体产生大量活性氧?" class="headerlink" title="甲醛如何诱导线粒体产生大量活性氧?"></a>甲醛如何诱导线粒体产生大量活性氧?</h3><p>线粒体是通过一个叫做“电子传递链”的复杂过程来产生能量(ATP)的。就像一条生产线,电子(e⁻)在这条生产线上被一步步传递,最终与我们吸入的氧气(O₂)结合生成水(H₂O),同时释放出大量能量。</p> +<h3 id="什么是活性氧?"><a class="header-anchor" href="#什么是活性氧?">¶</a>什么是活性氧?</h3> +<p><strong>活性氧(Reactive Oxygen Species, ROS)</strong> 是一类含氧的、化学性质极其活泼的分子或自由基的总称。常见的活性氧有 超氧阴离子(O₂⁻•)、羟自由基(•OH)、过氧化氢(H₂O₂)等。它们的特点之一是其都带有“未配对的电子”,这使得它们在化学上极不稳定,迫切地想要从其他分子那里“抢夺”电子来让自己稳定下来。</p> +<p>在正常情况下,我们身体会产生少量活性氧。它们是重要的信号分子,参与调节细胞生长、分化,并且是免疫细胞(如巨噬细胞)用来消灭入侵病原体(细菌、病毒)的“化学武器”。</p> +<p>一旦活性氧的产生<strong>远远超过</strong>了细胞自身的清除能力(细胞内有超氧化物歧化酶SOD等“警察”来控制它们),就会形成“<strong>氧化应激</strong>”(Oxidative Stress)状态。这些失控的“小流氓”就会在细胞内肆意破坏,攻击一切它们遇到的分子。</p> +<h3 id="甲醛如何诱导线粒体产生大量活性氧?"><a class="header-anchor" href="#甲醛如何诱导线粒体产生大量活性氧?">¶</a>甲醛如何诱导线粒体产生大量活性氧?</h3> +<p>线粒体是通过一个叫做“电子传递链”的复杂过程来产生能量(ATP)的。就像一条生产线,电子(e⁻)在这条生产线上被一步步传递,最终与我们吸入的氧气(O₂)结合生成水(H₂O),同时释放出大量能量。</p> <p>而甲醛及其代谢产物(如甲酸)会直接损伤电子传递链上的复合体蛋白(特别是复合体I和III)。这就像是破坏了生产线上的关键机器。</p> <p>当生产线上的机器受损或堵塞时,本该被有序传递的电子就会从传递链上“泄漏”出来。</p> <p>这些泄漏出来的高能电子,会直接传递给旁边无辜的氧气分子(O₂)。正常的氧气分子得到一个额外的电子后,就成为了极不稳定的<strong>超氧阴离子(O₂⁻•)</strong> (活性氧)。</p> -<h3 id="为什么活性氧能破坏细胞膜、蛋白质和DNA?"><a href="#为什么活性氧能破坏细胞膜、蛋白质和DNA?" class="headerlink" title="为什么活性氧能破坏细胞膜、蛋白质和DNA?"></a>为什么活性氧能破坏细胞膜、蛋白质和DNA?</h3><p>失控的活性氧会疯狂地从周围的生物大分子上抢夺电子,这个过程会导致这些大分子的化学结构被破坏,失去原有功能。</p> +<h3 id="为什么活性氧能破坏细胞膜、蛋白质和DNA?"><a class="header-anchor" href="#为什么活性氧能破坏细胞膜、蛋白质和DNA?">¶</a>为什么活性氧能破坏细胞膜、蛋白质和DNA?</h3> +<p>失控的活性氧会疯狂地从周围的生物大分子上抢夺电子,这个过程会导致这些大分子的化学结构被破坏,失去原有功能。</p> <p>细胞膜主要由<strong>磷脂双分子层</strong>构成,其中含有大量的<strong>不饱和脂肪酸</strong>。活性氧(特别是羟自由基•OH)会攻击不饱和脂肪酸中的双键,抢走一个电子,引发一个叫做“脂质过氧化”的链式反应。脂质过氧化会破坏细胞膜的流动性和完整性,使其变得僵硬、脆裂,最终导致细胞膜破裂,细胞内容物泄漏。</p> -<p> 而活性氧会攻击蛋白质侧链上的氨基酸(特别是半胱氨酸、甲硫氨酸等),使其氧化、交联(和甲醛的作用类似但原理不同),导致蛋白质变性,失去作为酶、结构蛋白或信号分子的功能。</p> -<p> 活性氧还会攻击DNA碱基(特别是鸟嘌呤G)和脱氧核糖骨架,导致<strong>碱基修饰、DNA单链或双链断裂</strong>。这会直接导致基因突变,干扰DNA的复制和转录,是诱发癌症的重要原因。</p> -<h3 id="什么是细胞的程序性死亡?"><a href="#什么是细胞的程序性死亡?" class="headerlink" title="什么是细胞的程序性死亡?"></a>什么是细胞的程序性死亡?</h3><p><strong>细胞程序性死亡(Programmed Cell Death)</strong>,最主要的形式是<strong>细胞凋亡(Apoptosis)</strong>。这并非细胞因损伤而发生的被动解体(那是“坏死”),而是细胞在接收到特定信号后,主动启动的一套基因编码的“自杀程序”。目的是清除体内不再需要、衰老或受到严重损伤(如无法修复的DNA损伤)的细胞,从而维持组织器官的稳定和健康。这是一个对机体有利的主动行为。</p> +<p>而活性氧会攻击蛋白质侧链上的氨基酸(特别是半胱氨酸、甲硫氨酸等),使其氧化、交联(和甲醛的作用类似但原理不同),导致蛋白质变性,失去作为酶、结构蛋白或信号分子的功能。</p> +<p>活性氧还会攻击DNA碱基(特别是鸟嘌呤G)和脱氧核糖骨架,导致<strong>碱基修饰、DNA单链或双链断裂</strong>。这会直接导致基因突变,干扰DNA的复制和转录,是诱发癌症的重要原因。</p> +<h3 id="什么是细胞的程序性死亡?"><a class="header-anchor" href="#什么是细胞的程序性死亡?">¶</a>什么是细胞的程序性死亡?</h3> +<p><strong>细胞程序性死亡(Programmed Cell Death)</strong>,最主要的形式是<strong>细胞凋亡(Apoptosis)</strong>。这并非细胞因损伤而发生的被动解体(那是“坏死”),而是细胞在接收到特定信号后,主动启动的一套基因编码的“自杀程序”。目的是清除体内不再需要、衰老或受到严重损伤(如无法修复的DNA损伤)的细胞,从而维持组织器官的稳定和健康。这是一个对机体有利的主动行为。</p> <p>在这个过程中每,细胞会主动收缩、染色质固缩、细胞核碎裂,最终形成多个被完整细胞膜包裹的“凋亡小体”,等待被免疫细胞吞噬清理。整个过程非常“干净”,不会引发周围的炎症。</p> -<p>在甲醛诱导的氧化应激中,由活性氧造成的大量、无法修复的DNA损伤和蛋白质损伤,本身就是最强烈的“死亡信号”。这个信号会激活细胞内一类叫做Bax和Bak的“促凋亡蛋白”。被激活的Bax/Bak蛋白会聚集到线粒体外膜上,像一个“打孔器”一样,在线粒体外膜上形成孔道。线粒体外膜被打孔后,原本储存在线粒体内部的一种关键蛋白——<strong>细胞色素C(Cytochrome C)</strong>,就会被释放到细胞质中。释放到细胞质中的细胞色素C,会激活一系列被称为 <strong>Caspase</strong> 的蛋白酶。它们一旦被激活,就会形成一个级联反应,像多米诺骨牌一样,一个激活下一个。被激活的Caspase会系统性地降解细胞内的关键蛋白质和DNA,最终导致细胞有序地解体,完成凋亡。</p> +<p>在甲醛诱导的氧化应激中,由活性氧造成的大量、无法修复的DNA损伤和蛋白质损伤,本身就是最强烈的“死亡信号”。这个信号会激活细胞内一类叫做Bax和Bak的“促凋亡蛋白”。被激活的Bax/Bak蛋白会聚集到线粒体外膜上,像一个“打孔器”一样,在线粒体外膜上形成孔道。线粒体外膜被打孔后,原本储存在线粒体内部的一种关键蛋白——<strong>细胞色素C(Cytochrome C)</strong>,就会被释放到细胞质中。释放到细胞质中的细胞色素C,会激活一系列被称为 <strong>Caspase</strong> 的蛋白酶。它们一旦被激活,就会形成一个级联反应,像多米诺骨牌一样,一个激活下一个。被激活的Caspase会系统性地降解细胞内的关键蛋白质和DNA,最终导致细胞有序地解体,完成凋亡。</p> <p><strong>“激活”在这里指的是一个剧烈的“构象变化”(Conformational Change)</strong>,即蛋白质从一种三维折叠形态,转变为另一种形态。</p> -<h4 id="什么是Bax-Bak蛋白?"><a href="#什么是Bax-Bak蛋白?" class="headerlink" title="什么是Bax/Bak蛋白?"></a>什么是Bax/Bak蛋白?</h4><p><strong>Bax和Bak</strong>是细胞内一个庞大家族——<strong>Bcl-2蛋白家族</strong>中的两个关键成员。Bax和Bak是在这里具有代表性的促凋亡派(Pro-apoptotic),Bcl-2、Bcl-xL 是 <strong>抗凋亡派(Anti-apoptotic):</strong> </p> +<h4 id="什么是Bax-Bak蛋白?"><a class="header-anchor" href="#什么是Bax-Bak蛋白?">¶</a>什么是Bax/Bak蛋白?</h4> +<p><strong>Bax和Bak</strong>是细胞内一个庞大家族——<strong>Bcl-2蛋白家族</strong>中的两个关键成员。Bax和Bak是在这里具有代表性的促凋亡派(Pro-apoptotic),Bcl-2、Bcl-xL 是 <strong>抗凋亡派(Anti-apoptotic):</strong></p> <p>在正常健康的细胞中,它们处于一种<strong>无害的、折叠起来的休眠状态</strong>。<strong>Bax</strong>大部分时间游荡在细胞质中。<strong>Bak</strong> 则停靠在线粒体的外膜上,但同样处于被抑制的休眠状态。</p> <p>当细胞遭受了大量、无法修复的DNA或蛋白质损伤时,这个信号会被细胞内的 <strong>p53蛋白</strong> 感知到。被激活的p53蛋白,会生产大量的一类被称为 “仅含BH3结构域蛋白”(BH3-only proteins)的小蛋白,例如 PUMA 和 Noxa。</p> -<h4 id="Bax-Bak-蛋白如何打孔?"><a href="#Bax-Bak-蛋白如何打孔?" class="headerlink" title="Bax/Bak 蛋白如何打孔?"></a>Bax/Bak 蛋白如何打孔?</h4><p>当Bax被激活后,它会暴露内部的<strong>疏水结构域</strong>。这个结构域极度“讨厌”水(细胞质的主要成分是水),而非常“喜欢”油性的环境。线粒体外膜正是一个由磷脂双分子层构成的“油性”环境。 因此,被激活的Bax会像一滴油会自动融入另一滴油一样,<strong>自发地从细胞质中转移并插入到线粒体外膜上</strong>。而已在膜上的Bak,被激活后则会更深、更稳定地嵌入膜中。</p> -<p>这是一个寡聚化(Oligomerization)过程。多个被激活的Bax/Bak分子在膜上相遇,会像乐高积木一样,通过彼此暴露出来的结构域互相识别并拼接在一起,形成大小不一的聚合体(Oligomer),有的像线形,有的像弧形,有的像不完整的环。这些Bax/Bak聚合体并<strong>不是</strong>贯穿膜形成一个隧道。相反,它们像楔子一样,大量地、浅浅地插入到线粒体外膜的<strong>外层</strong>。当越来越多的蛋白质“楔子”挤进这一层薄薄的膜时,会产生巨大的<strong>物理张力和弯曲应力</strong>。</p> -<p> 最终,线粒体外膜因为无法承受这种内部应力,就像一个被过度拉伸的气球一样被撕裂,形成的“孔道”或“裂口”,其边缘是由蛋白质和脂质分子共同构成的,被称为 “蛋白-脂质孔道”(Proteolipidic Pore)。</p> -<h4 id="为什么“严重损伤”会激活p53蛋白?"><a href="#为什么“严重损伤”会激活p53蛋白?" class="headerlink" title="为什么“严重损伤”会激活p53蛋白?"></a>为什么“严重损伤”会激活p53蛋白?</h4><p>在正常、安逸的细胞中,p53蛋白一被生产出来,就会被一个叫做 <strong>MDM2</strong> 的蛋白“盯上”。MDM2会给p53贴上一个叫做 “泛素”(Ubiquitin)的标签,被贴上标签的p53会被送到细胞的“垃圾处理厂”——<strong>蛋白酶体</strong>中迅速降解。因此,正常细胞里的p53蛋白水平极低。</p> +<h4 id="Bax-Bak-蛋白如何打孔?"><a class="header-anchor" href="#Bax-Bak-蛋白如何打孔?">¶</a>Bax/Bak 蛋白如何打孔?</h4> +<p>当Bax被激活后,它会暴露内部的<strong>疏水结构域</strong>。这个结构域极度“讨厌”水(细胞质的主要成分是水),而非常“喜欢”油性的环境。线粒体外膜正是一个由磷脂双分子层构成的“油性”环境。 因此,被激活的Bax会像一滴油会自动融入另一滴油一样,<strong>自发地从细胞质中转移并插入到线粒体外膜上</strong>。而已在膜上的Bak,被激活后则会更深、更稳定地嵌入膜中。</p> +<p>这是一个寡聚化(Oligomerization)过程。多个被激活的Bax/Bak分子在膜上相遇,会像乐高积木一样,通过彼此暴露出来的结构域互相识别并拼接在一起,形成大小不一的聚合体(Oligomer),有的像线形,有的像弧形,有的像不完整的环。这些Bax/Bak聚合体并<strong>不是</strong>贯穿膜形成一个隧道。相反,它们像楔子一样,大量地、浅浅地插入到线粒体外膜的<strong>外层</strong>。当越来越多的蛋白质“楔子”挤进这一层薄薄的膜时,会产生巨大的<strong>物理张力和弯曲应力</strong>。</p> +<p>最终,线粒体外膜因为无法承受这种内部应力,就像一个被过度拉伸的气球一样被撕裂,形成的“孔道”或“裂口”,其边缘是由蛋白质和脂质分子共同构成的,被称为 “蛋白-脂质孔道”(Proteolipidic Pore)。</p> +<h4 id="为什么“严重损伤”会激活p53蛋白?"><a class="header-anchor" href="#为什么“严重损伤”会激活p53蛋白?">¶</a>为什么“严重损伤”会激活p53蛋白?</h4> +<p>在正常、安逸的细胞中,p53蛋白一被生产出来,就会被一个叫做 <strong>MDM2</strong> 的蛋白“盯上”。MDM2会给p53贴上一个叫做 “泛素”(Ubiquitin)的标签,被贴上标签的p53会被送到细胞的“垃圾处理厂”——<strong>蛋白酶体</strong>中迅速降解。因此,正常细胞里的p53蛋白水平极低。</p> <p>当 “严重损伤”<strong>,尤其是</strong>DNA双链断裂(这被视为细胞最危急的损伤之一)发生时,DNA断裂处会立刻吸引并激活一批蛋白,其中最关键的是一类激酶(Kinase),比如<strong>ATM</strong>和<strong>ATR</strong>。激酶是一种能给其他蛋白质“安装”上磷酸基团(-PO₃²⁻)的工具酶。</p> -<p>被激活的ATM/ATR激酶,会立刻找到 MDM2,并给它装上好几个磷酸基团。被磷酸化后的MDM2结构发生改变,无法再识别和结合p53。 与此同时,ATM/ATR 等激酶也会给 p53 蛋白本身装上磷酸基团。这个过程不仅让p53无法被MDM2识别,更重要的是,它改变了p53的构象。</p> -<p>对于p53来说,最基础的激活,就是摆脱 MDM2 的控制,不再被降解。这使得 p53 蛋白可以在细胞核内大量、稳定地积累起来,被磷酸化等一系列化学修饰后,p53蛋白的三维结构会发生精妙的变化。这种变化会暴露p53内部一个关键的功能区——<strong>“DNA结合域”</strong>。同时,它会促使四个p53蛋白分子结合在一起,形成一个<strong>四聚体(Tetramer)</strong>。 </p> -<h5 id="为什么-MDM2-会盯上-p53?"><a href="#为什么-MDM2-会盯上-p53?" class="headerlink" title="为什么 MDM2 会盯上 p53?"></a>为什么 MDM2 会盯上 p53?</h5><p>在MDM2蛋白的N端(头部),有一个精心构造的、深邃的<strong>疏水性口袋(hydrophobic pocket)</strong>,就像手套一样。而在p53蛋白的N端(反式激活域),有一段α-螺旋区域。这段螺旋上有三个关键的氨基酸残基——<strong>苯丙氨酸(Phe19)、色氨酸(Trp23)和亮氨酸(Leu26)</strong>。这三个氨基酸像三根关键的“手指”,完美地伸入并契合MDM2的那个手套中。</p> -<h5 id="p53被激活后如何“下令”生产PUMA等蛋白?"><a href="#p53被激活后如何“下令”生产PUMA等蛋白?" class="headerlink" title="p53被激活后如何“下令”生产PUMA等蛋白?"></a>p53被激活后如何“下令”生产PUMA等蛋白?</h5><p> PUMA这个蛋白,它的“设计图纸”编码在一段叫做 _PUMA_(也称 _BBC3_)的基因里。在这段基因的上游,有一段特殊的DNA序列,叫做 “启动子”(Promoter)。而PUMA基因的启动子上,有 p53 蛋白能够识别并结合的特定“停泊位点”,称为 “p53响应元件”(p53 Response Element)。</p> +<p>被激活的ATM/ATR激酶,会立刻找到 MDM2,并给它装上好几个磷酸基团。被磷酸化后的MDM2结构发生改变,无法再识别和结合p53。 与此同时,ATM/ATR 等激酶也会给 p53 蛋白本身装上磷酸基团。这个过程不仅让p53无法被MDM2识别,更重要的是,它改变了p53的构象。</p> +<p>对于p53来说,最基础的激活,就是摆脱 MDM2 的控制,不再被降解。这使得 p53 蛋白可以在细胞核内大量、稳定地积累起来,被磷酸化等一系列化学修饰后,p53蛋白的三维结构会发生精妙的变化。这种变化会暴露p53内部一个关键的功能区——<strong>“DNA结合域”</strong>。同时,它会促使四个p53蛋白分子结合在一起,形成一个<strong>四聚体(Tetramer)</strong>。</p> +<h5 id="为什么-MDM2-会盯上-p53?"><a class="header-anchor" href="#为什么-MDM2-会盯上-p53?">¶</a>为什么 MDM2 会盯上 p53?</h5> +<p>在MDM2蛋白的N端(头部),有一个精心构造的、深邃的<strong>疏水性口袋(hydrophobic pocket)</strong>,就像手套一样。而在p53蛋白的N端(反式激活域),有一段α-螺旋区域。这段螺旋上有三个关键的氨基酸残基——<strong>苯丙氨酸(Phe19)、色氨酸(Trp23)和亮氨酸(Leu26)</strong>。这三个氨基酸像三根关键的“手指”,完美地伸入并契合MDM2的那个手套中。</p> +<h5 id="p53被激活后如何“下令”生产PUMA等蛋白?"><a class="header-anchor" href="#p53被激活后如何“下令”生产PUMA等蛋白?">¶</a>p53被激活后如何“下令”生产PUMA等蛋白?</h5> +<p>PUMA这个蛋白,它的“设计图纸”编码在一段叫做 <em>PUMA</em>(也称 <em>BBC3</em>)的基因里。在这段基因的上游,有一段特殊的DNA序列,叫做 “启动子”(Promoter)。而PUMA基因的启动子上,有 p53 蛋白能够识别并结合的特定“停泊位点”,称为 “p53响应元件”(p53 Response Element)。</p> <p>被激活的p53四聚体,凭借其暴露出来的DNA结合域,会精准地找到并牢牢地结合在PUMA基因的这个“停泊位点”上。一旦结合,p53 自身就会像一块磁铁,吸引来细胞核内负责“抄写”基因的庞大机器——<strong>RNA聚合酶II</strong>以及其他大量的辅助蛋白。这个庞大的蛋白质复合体,就是负责执行命令的“抄写员”。</p> <p>“抄写员”以DNA为模板,“抄写”出一段信使RNA(mRNA)。这段mRNA会离开细胞核进入细胞质,并被核糖体(蛋白质的“生产工厂”)读取,最终翻译、生产出我们需要的<strong>PUMA蛋白</strong>。</p> <p>这就是基因转录。</p> -<h4 id="为什么-DNA-的断裂会吸引激酶?"><a href="#为什么-DNA-的断裂会吸引激酶?" class="headerlink" title="为什么 DNA 的断裂会吸引激酶?"></a>为什么 DNA 的断裂会吸引激酶?</h4><p>在正常细胞中,ATM是以无活性的二聚体(两个ATM蛋白抱在一起)形式存在的。这个“拥抱”的姿态,恰好就掩盖了彼此的“催化核心区”。 激活,就是让这俩分开。</p> +<h4 id="为什么-DNA-的断裂会吸引激酶?"><a class="header-anchor" href="#为什么-DNA-的断裂会吸引激酶?">¶</a>为什么 DNA 的断裂会吸引激酶?</h4> +<p>在正常细胞中,ATM是以无活性的二聚体(两个ATM蛋白抱在一起)形式存在的。这个“拥抱”的姿态,恰好就掩盖了彼此的“催化核心区”。 激活,就是让这俩分开。</p> <p>当DNA发生双链断裂时,会暴露出两个<strong>DNA断端</strong>。这在正常的、连续的DNA双螺旋结构中是绝对不会出现的。这个裸露的、不连续的断端,就是一个<strong>强烈的物理异常信号</strong>。</p> <p>细胞内有一组蛋白质,叫做<strong>MRN复合体</strong>(由Mre11、Rad50、Nbs1三个蛋白组成)。</p> <p><strong>Mre11和Rad50</strong> 能特异性地识别并抓住DNA的断端,像桥梁一样将两个断端物理性地拉近,防止它们飘远。MRN复合体一旦抓住了DNA断端,它自身的构象就会发生改变。这种改变使得它能够吸引在细胞核内游走的、处于休眠二聚体状态的ATM。MRN复合体(特别是其中的Nbs1蛋白)上会暴露出一个能与ATM二聚体结合的“接口”。这种分子间的特异性亲和力,使得ATM被“吸引”并<strong>物理性地富集</strong>到DNA断裂的地方。</p> <p>当大量的ATM二聚体被招募到MRN复合体标记的DNA断端附近时,DNA断端的物理存在,加上MRN复合体的“撬动”作用,会诱导ATM二聚体的构象发生变化,促使这俩解离,变成两个独立的单体。</p> -<p> 解离后的ATM单体,其被隐藏的“催化核心区”立刻暴露了出来。一个ATM单体会立刻给另一个(或自己)的特定位点(如丝氨酸1981位点)“安装”上一个磷酸基团。这是个 “自我磷酸化” 的过程,会使其构象进一步稳定在完全激活的状态。</p> -<h1 id="先到这儿吧,我要吃炒粉了"><a href="#先到这儿吧,我要吃炒粉了" class="headerlink" title="先到这儿吧,我要吃炒粉了"></a>先到这儿吧,我要吃炒粉了</h1>]]></content> +<p>解离后的ATM单体,其被隐藏的“催化核心区”立刻暴露了出来。一个ATM单体会立刻给另一个(或自己)的特定位点(如丝氨酸1981位点)“安装”上一个磷酸基团。这是个 “自我磷酸化” 的过程,会使其构象进一步稳定在完全激活的状态。</p> +<h1>先到这儿吧,我要吃炒粉了</h1> +]]></content> <tags> <tag>Medicine</tag> </tags> @@ -2671,29 +2935,38 @@ await prisma.$transaction(async tx => { <title>肠易激综合征 (IBS) 的病理学与药物治疗</title> <url>/2025/06/30/ibs/</url> <content><![CDATA[<p>肠易激综合征 (Irritable Bowel Syndrome, IBS) 是一种常见的功能性胃肠病。其核心特征是在没有发现任何器质性病变(如炎症、溃疡或肿瘤)的情况下,患者长期经历腹痛、腹胀,并伴有排便习惯的改变(腹泻、便秘或两者交替)。</p> -<h3 id="一、-肠易激综合征的病理生理学"><a href="#一、-肠易激综合征的病理生理学" class="headerlink" title="一、 肠易激综合征的病理生理学"></a>一、 肠易激综合征的病理生理学</h3><p>IBS 的病理生理机制非常复杂,并非由单一原因导致,而是多种因素相互作用的结果。目前的医学研究认为,其主要与以下几个核心机制有关:</p> -<h4 id="1-脑-肠轴功能紊乱-Disorders-of-the-Brain-Gut-Axis"><a href="#1-脑-肠轴功能紊乱-Disorders-of-the-Brain-Gut-Axis" class="headerlink" title="1. 脑-肠轴功能紊乱 (Disorders of the Brain-Gut Axis)"></a>1. 脑-肠轴功能紊乱 (Disorders of the Brain-Gut Axis)</h4><p>这是 IBS 最核心的病理机制。大脑和肠道通过神经、内分泌和免疫系统形成一个双向沟通的“脑-肠轴”。在 IBS 患者中,这个轴的功能出现紊乱。</p> +<h3 id="一、-肠易激综合征的病理生理学"><a class="header-anchor" href="#一、-肠易激综合征的病理生理学">¶</a>一、 肠易激综合征的病理生理学</h3> +<p>IBS 的病理生理机制非常复杂,并非由单一原因导致,而是多种因素相互作用的结果。目前的医学研究认为,其主要与以下几个核心机制有关:</p> +<h4 id="1-脑-肠轴功能紊乱-Disorders-of-the-Brain-Gut-Axis"><a class="header-anchor" href="#1-脑-肠轴功能紊乱-Disorders-of-the-Brain-Gut-Axis">¶</a>1. 脑-肠轴功能紊乱 (Disorders of the Brain-Gut Axis)</h4> +<p>这是 IBS 最核心的病理机制。大脑和肠道通过神经、内分泌和免疫系统形成一个双向沟通的“脑-肠轴”。在 IBS 患者中,这个轴的功能出现紊乱。</p> <ul> <li><strong>自上而下:</strong> 心理压力、焦虑、抑郁等负面情绪可以直接通过大脑影响肠道的运动、感觉和分泌功能,从而诱发或加重症状。</li> <li><strong>自下而上:</strong> 肠道内的信号(如食物、气体、肠道菌群代谢产物)被过度放大后传给大脑,导致大脑对这些正常刺激产生过度反应,表现为疼痛和不适。</li> </ul> -<h4 id="2-内脏高敏感性-Visceral-Hypersensitivity"><a href="#2-内脏高敏感性-Visceral-Hypersensitivity" class="headerlink" title="2. 内脏高敏感性 (Visceral Hypersensitivity)"></a>2. 内脏高敏感性 (Visceral Hypersensitivity)</h4><p>这是指 IBS 患者的肠道对各种刺激(如食物、气体、肠壁的牵拉)异常敏感。正常人可以耐受的肠道内压力或活动,在 IBS 患者身上却会引发强烈的腹痛、急便感或不适。这种“放大”的感觉是 IBS 腹痛的主要原因。</p> -<h4 id="3-胃肠动力异常-Altered-Gut-Motility"><a href="#3-胃肠动力异常-Altered-Gut-Motility" class="headerlink" title="3. 胃肠动力异常 (Altered Gut Motility)"></a>3. 胃肠动力异常 (Altered Gut Motility)</h4><p>肠道肌肉的收缩和舒张节律出现问题,导致食物和粪便在肠道内的转运速度异常。</p> +<h4 id="2-内脏高敏感性-Visceral-Hypersensitivity"><a class="header-anchor" href="#2-内脏高敏感性-Visceral-Hypersensitivity">¶</a>2. 内脏高敏感性 (Visceral Hypersensitivity)</h4> +<p>这是指 IBS 患者的肠道对各种刺激(如食物、气体、肠壁的牵拉)异常敏感。正常人可以耐受的肠道内压力或活动,在 IBS 患者身上却会引发强烈的腹痛、急便感或不适。这种“放大”的感觉是 IBS 腹痛的主要原因。</p> +<h4 id="3-胃肠动力异常-Altered-Gut-Motility"><a class="header-anchor" href="#3-胃肠动力异常-Altered-Gut-Motility">¶</a>3. 胃肠动力异常 (Altered Gut Motility)</h4> +<p>肠道肌肉的收缩和舒张节律出现问题,导致食物和粪便在肠道内的转运速度异常。</p> <ul> <li><strong>转运过快:</strong> 肠道内容物过快通过结肠,水分来不及被充分吸收,导致腹泻(IBS-D)。</li> <li><strong>转运过慢:</strong> 肠道蠕动乏力,粪便在结肠内停留时间过长,水分被过度吸收,导致便秘(IBS-C)。</li> <li><strong>节律紊乱:</strong> 有时快有时慢,导致腹泻与便秘交替出现(IBS-M)。</li> </ul> -<h4 id="4-肠道微生态失调-Alteration-in-Gut-Microbiota"><a href="#4-肠道微生态失调-Alteration-in-Gut-Microbiota" class="headerlink" title="4. 肠道微生态失调 (Alteration in Gut Microbiota)"></a>4. 肠道微生态失调 (Alteration in Gut Microbiota)</h4><p>IBS 患者的肠道菌群组成和功能与健康人存在差异。有害菌可能增多,有益菌(如双歧杆菌、乳酸杆菌)可能减少。这些失调的菌群会影响肠道屏障功能、产生过多气体、并激活免疫系统,导致腹胀和腹泻。</p> -<h4 id="5-肠道低度炎症与免疫激活-Low-Grade-Inflammation-and-Immune-Activation"><a href="#5-肠道低度炎症与免疫激活-Low-Grade-Inflammation-and-Immune-Activation" class="headerlink" title="5. 肠道低度炎症与免疫激活 (Low-Grade Inflammation and Immune Activation)"></a>5. 肠道低度炎症与免疫激活 (Low-Grade Inflammation and Immune Activation)</h4><p>部分 IBS 患者的肠道黏膜中可以观察到轻微的炎症反应,例如肥大细胞等免疫细胞数量增多并被激活。这些细胞会释放组胺、5-羟色胺等物质,直接刺激肠道神经,引起疼痛和动力异常。这种情况尤其在感染性肠炎后发生的 IBS(PI-IBS)中更为常见。</p> -<h4 id="6-遗传与饮食因素"><a href="#6-遗传与饮食因素" class="headerlink" title="6. 遗传与饮食因素"></a>6. 遗传与饮食因素</h4><ul> +<h4 id="4-肠道微生态失调-Alteration-in-Gut-Microbiota"><a class="header-anchor" href="#4-肠道微生态失调-Alteration-in-Gut-Microbiota">¶</a>4. 肠道微生态失调 (Alteration in Gut Microbiota)</h4> +<p>IBS 患者的肠道菌群组成和功能与健康人存在差异。有害菌可能增多,有益菌(如双歧杆菌、乳酸杆菌)可能减少。这些失调的菌群会影响肠道屏障功能、产生过多气体、并激活免疫系统,导致腹胀和腹泻。</p> +<h4 id="5-肠道低度炎症与免疫激活-Low-Grade-Inflammation-and-Immune-Activation"><a class="header-anchor" href="#5-肠道低度炎症与免疫激活-Low-Grade-Inflammation-and-Immune-Activation">¶</a>5. 肠道低度炎症与免疫激活 (Low-Grade Inflammation and Immune Activation)</h4> +<p>部分 IBS 患者的肠道黏膜中可以观察到轻微的炎症反应,例如肥大细胞等免疫细胞数量增多并被激活。这些细胞会释放组胺、5-羟色胺等物质,直接刺激肠道神经,引起疼痛和动力异常。这种情况尤其在感染性肠炎后发生的 IBS(PI-IBS)中更为常见。</p> +<h4 id="6-遗传与饮食因素"><a class="header-anchor" href="#6-遗传与饮食因素">¶</a>6. 遗传与饮食因素</h4> +<ul> <li><strong>遗传:</strong> IBS具有一定的家族聚集性,提示可能存在遗传易感性。</li> <li><strong>饮食:</strong> 某些食物,特别是含有高<strong>FODMAPs</strong>(可发酵的寡糖、双糖、单糖和多元醇)的食物,在小肠内难以被吸收,进入大肠后被细菌快速发酵,产生大量气体并增加肠道渗透压,从而诱发腹胀、腹痛和腹泻。</li> </ul> -<h3 id="二、-肠易激综合征的药物治疗"><a href="#二、-肠易激综合征的药物治疗" class="headerlink" title="二、 肠易激综合征的药物治疗"></a>二、 肠易激综合征的药物治疗</h3><blockquote> +<h3 id="二、-肠易激综合征的药物治疗"><a class="header-anchor" href="#二、-肠易激综合征的药物治疗">¶</a>二、 肠易激综合征的药物治疗</h3> +<blockquote> <p>IBS的治疗需要个体化,所有药物都应在医生指导下使用。医生应该根据具体的 IBS 亚型(腹泻型、便秘型、混合型)和主要症状来选择最合适的药物。</p> </blockquote> -<h4 id="针对主要症状的药物"><a href="#针对主要症状的药物" class="headerlink" title="针对主要症状的药物"></a>针对主要症状的药物</h4><p><strong>1. 针对腹痛和腹胀(解痉药)</strong></p> +<h4 id="针对主要症状的药物"><a class="header-anchor" href="#针对主要症状的药物">¶</a>针对主要症状的药物</h4> +<p><strong>1. 针对腹痛和腹胀(解痉药)</strong></p> <p>这类药物通过放松肠道平滑肌,缓解肠道痉挛来减轻疼痛。</p> <ul> <li><strong>匹维溴铵 (Pinaverium Bromide):</strong> 作用于肠道平滑肌的钙离子通道,选择性高,副作用较小。</li> @@ -2713,7 +2986,8 @@ await prisma.$transaction(async tx => { <ul> <li><strong>容积性泻药(如欧车前、聚卡波非钙):</strong> 通过吸收水分增加粪便体积,刺激肠道蠕动。使用时需饮用足量水,否则可能加重便秘。</li> <li><strong>渗透性泻药(如聚乙二醇 PEG、乳果糖):</strong> 通过在肠道内形成高渗环境,将水分保留在肠腔内,软化粪便,促进排便。相对安全,适合长期使用。</li> -<li><strong>促分泌药:</strong><ul> +<li><strong>促分泌药:</strong> +<ul> <li><strong>鲁比前列酮 (Lubiprostone):</strong> 激活肠道氯离子通道,增加肠液分泌,软化粪便。</li> <li><strong>利那洛肽 (Linaclotide)、普卡那肽 (Plecanatide):</strong> 激活鸟苷酸环化酶-C,促进肠液分泌,并能一定程度上缓解腹痛。</li> </ul> @@ -2740,7 +3014,6 @@ await prisma.$transaction(async tx => { <content><![CDATA[<p>不知道我们所说的闪烁是不是一个东西,在我的笔记本上,闪烁是指偶发的屏幕中出现部分彩色雪花。</p> <p>我使用 Pop!_OS,此发行版使用 EFI 启动,故而可以在 <code>/boot/efi/loader/loader.conf</code> 中加上:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">options quiet splash amdgpu.dcdebugmask=0x10 amdgpu.sg_display=0</span><br></pre></td></tr></table></figure> - <p>对于其他使用 EFI 或 GRUB 启动的发行版也可以添加类似的参数尝试尝试。</p> ]]></content> <tags> @@ -2750,48 +3023,53 @@ await prisma.$transaction(async tx => { <entry> <title>NestJS bullmq 邮件发送业务中的小 tips</title> <url>/2025/05/07/nestjs-bullmq-mail-business/</url> - <content><![CDATA[<p>在 BullMQ(以及它在 NestJS 里包装的 <code>@Processor</code>/<code>WorkerHost</code>)里,整个生命周期大致是这样的:</p> + <content><![CDATA[<p>在 BullMQ(以及它在 NestJS 里包装的 <code>@Processor</code>/<code>WorkerHost</code>)里,整个生命周期大致是这样的:</p> <ol> -<li>队列(在 NestJS 里由 <code>@Processor</code> 装饰的类)会被一个底层的 <code>Worker</code> 订阅。 </li> -<li>有新任务(job)进来时,Worker 会调用写在该类里的 <code>async process(job: Job)</code> 方法。 </li> -<li>如果 <code>process()</code> 正常返回(即没有抛异常),Job 就被标记为 completed,然后才会去触发所有注册了 <code>@OnWorkerEvent('completed')</code> 的回调。</li> +<li>队列(在 NestJS 里由 <code>@Processor</code> 装饰的类)会被一个底层的 <code>Worker</code> 订阅。</li> +<li>有新任务(job)进来时,Worker 会调用写在该类里的 <code>async process(job: Job)</code> 方法。</li> +<li>如果 <code>process()</code> 正常返回(即没有抛异常),Job 就被标记为 completed,然后才会去触发所有注册了 <code>@OnWorkerEvent('completed')</code> 的回调。</li> </ol> <p>也就是说:</p> <ul> -<li><code>process</code>:是真正“干活”的地方,收到 job 之后立刻被调用,任何主业务逻辑(发邮件/写数据库/第三方请求等)都应该放这里。 </li> +<li><code>process</code>:是真正“干活”的地方,收到 job 之后立刻被调用,任何主业务逻辑(发邮件/写数据库/第三方请求等)都应该放这里。</li> <li><code>onCompleted</code>:只是一个事件监听器,在 job 已经成功完成之后 才会被触发,不会影响 job 的重试逻辑(也就是说,在这里抛错,job 已经算完成了,也不会重试)。</li> </ul> <p>而我在此处的业务目的是 “用队列来做可靠的、可重试的邮件发送”,那么一定要把发送邮件的逻辑写到 <code>process()</code> 里,这样在 <code>commandBus.execute(new SendMailCommand(...))</code> 抛错时,BullMQ 会根据创建 JOB 时的重试策略(retry、backoff 等)自动重新入队。而把它放到 <code>onCompleted()</code>,只相当于 job 成功完成后的“事后通知”,一旦失败不会再重试,也无法利用 BullMQ 的锁、超时、重试机制。</p> -<p>举个最简化的调整示例,删掉 <code>onCompleted</code>,把真正的发信放到 <code>process</code>: </p> +<p>举个最简化的调整示例,删掉 <code>onCompleted</code>,把真正的发信放到 <code>process</code>:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">// ... existing imports ...</span><br><span class="line"></span><br><span class="line">@Processor(process.env.MAILER_QUEUE_NAME || "gcpm-mailer")</span><br><span class="line">export class BullMQMailerProcesser extends WorkerHost {</span><br><span class="line"> constructor(</span><br><span class="line"> private readonly commandBus: CommandBus,</span><br><span class="line"> private readonly logger: LoggingService,</span><br><span class="line"> ) {</span><br><span class="line"> super();</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> // ① 当有新 job 拉取到时,这个方法会被调用</span><br><span class="line"> public async process(job: Job): Promise<void> {</span><br><span class="line"> const mailAggregate = new Mail(job.data.mail);</span><br><span class="line"> try {</span><br><span class="line"> await this.commandBus.execute(new SendMailCommand(mailAggregate));</span><br><span class="line"> } catch (err) {</span><br><span class="line"> this.logger.error(`邮件发送失败,jobId=${job.id}`, err);</span><br><span class="line"> // 抛出错误,触发重试或失败</span><br><span class="line"> throw err;</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> // ② onCompleted 仅在 process() 正常返回后触发,</span><br><span class="line"> // 不建议在这里执行核心业务(也无法触发重试)。</span><br><span class="line"> // @OnWorkerEvent("completed")</span><br><span class="line"> // async onCompleted(job: Job) { … }</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - <p>参考 BullMQ 官方文档:</p> <ul> -<li>“Workers → Sandboxed processors”:Worker 拉到 job 就调用注册的处理函数,然后根据返回/抛错把 job 标记成 completed 或 failed。 </li> +<li>“Workers → Sandboxed processors”:Worker 拉到 job 就调用注册的处理函数,然后根据返回/抛错把 job 标记成 completed 或 failed。</li> <li>“Events → OnJobCompleted”:completed 事件只是一个监听钩子,不会参与重试。</li> </ul> <hr> <p>而 重试次数本身并没有一个硬性上限,完全由添加 Job 时通过 <code>attempts</code> 这个选项来控制:</p> <ul> -<li>默认情况下,如果不传 <code>attempts</code>(或不在 <code>defaultJobOptions</code> 里配置),Job 不会自动重试(相当于 <code>attempts = 0</code>)。 </li> -<li>如果在 <code>queue.add()</code>(或全局 <code>defaultJobOptions</code>)里设置了 <code>attempts: N</code>,那么 BullMQ 最多会让该 Job 运行 N 次(也就是初始执行 + N−1 次重试,或者根据文档含义最多触发 N 次失败) ,失败后才算真正移入失败集合。 </li> +<li>默认情况下,如果不传 <code>attempts</code>(或不在 <code>defaultJobOptions</code> 里配置),Job 不会自动重试(相当于 <code>attempts = 0</code>)。</li> +<li>如果在 <code>queue.add()</code>(或全局 <code>defaultJobOptions</code>)里设置了 <code>attempts: N</code>,那么 BullMQ 最多会让该 Job 运行 N 次(也就是初始执行 + N−1 次重试,或者根据文档含义最多触发 N 次失败) ,失败后才算真正移入失败集合。</li> <li><code>attempts</code> 可以是任意的正整数(受 JavaScript <code>Number</code> 范围限制),BullMQ 本身不会再做额外的上限检查。</li> </ul> <p>示例(给某封邮件最多重试 3 次):</p> <figure class="highlight ts"><table><tr><td class="code"><pre><span class="line"><span class="keyword">await</span> <span class="variable language_">this</span>.<span class="property">mailerQueue</span>.<span class="title function_">add</span>(</span><br><span class="line"> id,</span><br><span class="line"> { <span class="attr">mail</span>: <span class="keyword">new</span> <span class="title class_">Mail</span>(<span class="comment">/*…*/</span> ) },</span><br><span class="line"> {</span><br><span class="line"> <span class="attr">attempts</span>: <span class="number">3</span>, <span class="comment">// 最多尝试 3 次</span></span><br><span class="line"> <span class="attr">backoff</span>: { <span class="comment">// 重试时的延迟策略(可选)</span></span><br><span class="line"> <span class="attr">type</span>: <span class="string">'exponential'</span>,</span><br><span class="line"> <span class="attr">delay</span>: <span class="number">1000</span>,</span><br><span class="line"> },</span><br><span class="line"> },</span><br><span class="line">);</span><br></pre></td></tr></table></figure> - <hr> <p>还有一个需要注意的地方,在我的业务中,邮件发送的是一种时间区间报告,这个报告包含了过去二十四小时的一些系统中的事件,但如果重试有延迟策略或重试本身就有计算成本的话,这封邮件就不是 “过去二十四小时” 的了,因为重试带来了一个真空期。</p> <p>换言之,这个问题本质上是——重试导致「发送时刻」与「原始 24 小时窗口」错开,从而让邮件里报出来的数据不再精确。常见的解决思路就是:把「窗口定义」或者「报表内容」在调度时就固化下来,真正的队列任务只负责发送,而不再实时去重新计算时间区间。</p> <p>我想到了两种解决方案:</p> -<p>一、任务参数里带上「时间区间」<br> 在 enqueue 的时候,就算出 windowStart/windowEnd,然后把它放到 <code>job.data</code> 里。无论后面 <code>process</code> 什么时候真正跑,都是基于同一个时间区间去查询:</p> +<p>一、任务参数里带上「时间区间」<br> +在 enqueue 的时候,就算出 windowStart/windowEnd,然后把它放到 <code>job.data</code> 里。无论后面 <code>process</code> 什么时候真正跑,都是基于同一个时间区间去查询:</p> <figure class="highlight ts"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 调度时</span></span><br><span class="line"><span class="keyword">const</span> now = <span class="keyword">new</span> <span class="title class_">Date</span>();</span><br><span class="line"><span class="keyword">const</span> windowStart = <span class="keyword">new</span> <span class="title class_">Date</span>(now.<span class="title function_">getTime</span>() - <span class="number">24</span> * <span class="number">60</span> * <span class="number">60</span> * <span class="number">1000</span>);</span><br><span class="line"><span class="keyword">await</span> <span class="variable language_">this</span>.<span class="property">mailerQueue</span>.<span class="title function_">add</span>(</span><br><span class="line"> id,</span><br><span class="line"> {</span><br><span class="line"> <span class="attr">mail</span>: <span class="keyword">new</span> <span class="title class_">Mail</span>({</span><br><span class="line"> ...options,</span><br><span class="line"> id,</span><br><span class="line"> <span class="attr">sentAt</span>: now,</span><br><span class="line"> <span class="attr">status</span>: <span class="title class_">MailStatus</span>.<span class="property">PENDING</span>,</span><br><span class="line"> windowStart,</span><br><span class="line"> <span class="attr">windowEnd</span>: now,</span><br><span class="line"> }),</span><br><span class="line"> },</span><br><span class="line"> {</span><br><span class="line"> <span class="attr">attempts</span>: <span class="number">3</span>,</span><br><span class="line"> <span class="attr">backoff</span>: { <span class="attr">type</span>: <span class="string">'exponential'</span>, <span class="attr">delay</span>: <span class="number">1000</span> },</span><br><span class="line"> },</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line"><span class="comment">// process 里</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">async</span> <span class="title function_">process</span>(<span class="params"><span class="attr">job</span>: <span class="title class_">Job</span></span>) {</span><br><span class="line"> <span class="keyword">const</span> { windowStart, windowEnd } = job.<span class="property">data</span>.<span class="property">mail</span>;</span><br><span class="line"> <span class="comment">// ① 只查询 [windowStart, windowEnd] 的事件</span></span><br><span class="line"> <span class="keyword">const</span> events = <span class="keyword">await</span> <span class="variable language_">this</span>.<span class="property">reportService</span>.<span class="title function_">findEvents</span>(windowStart, windowEnd);</span><br><span class="line"> <span class="keyword">const</span> reportHtml = <span class="keyword">await</span> <span class="variable language_">this</span>.<span class="property">reportService</span>.<span class="title function_">renderReport</span>(events);</span><br><span class="line"> <span class="keyword">await</span> <span class="variable language_">this</span>.<span class="property">commandBus</span>.<span class="title function_">execute</span>(<span class="keyword">new</span> <span class="title class_">SendMailCommand</span>(job.<span class="property">data</span>.<span class="property">mail</span>, reportHtml));</span><br><span class="line">}</span><br></pre></td></tr></table></figure> -<p> ➜ 这样无是马上执行还是几次重试后才执行,数据规则都不会变。</p> -<p>二、预先生成「静态报表内容」,挂到队列里<br> 如果计算成本很高,或者怕重复查询数据开销大,也可以在调度时就把最终的 HTML/Text/附件 都先打好,然后作为 <code>job.data</code> 传进去,真正的 <code>process()</code> 只做一次“发送”即可:<br> <figure class="highlight ts"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 调度时:先生成报告</span></span><br><span class="line"><span class="keyword">const</span> now = <span class="keyword">new</span> <span class="title class_">Date</span>();</span><br><span class="line"><span class="keyword">const</span> windowStart = <span class="keyword">new</span> <span class="title class_">Date</span>(now.<span class="title function_">getTime</span>() - <span class="number">24</span>*<span class="number">3600</span>*<span class="number">1000</span>);</span><br><span class="line"><span class="keyword">const</span> events = <span class="keyword">await</span> <span class="variable language_">this</span>.<span class="property">reportService</span>.<span class="title function_">findEvents</span>(windowStart, now);</span><br><span class="line"><span class="keyword">const</span> reportHtml = <span class="keyword">await</span> <span class="variable language_">this</span>.<span class="property">reportService</span>.<span class="title function_">renderReport</span>(events);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 把静态内容塞到队列</span></span><br><span class="line"><span class="keyword">await</span> <span class="variable language_">this</span>.<span class="property">mailerQueue</span>.<span class="title function_">add</span>(</span><br><span class="line"> id,</span><br><span class="line"> {</span><br><span class="line"> <span class="attr">mail</span>: <span class="keyword">new</span> <span class="title class_">Mail</span>({ <span class="comment">/*…*/</span>, windowStart, <span class="attr">windowEnd</span>: now }),</span><br><span class="line"> reportHtml, <span class="comment">// <- 预渲染好的文本/HTML</span></span><br><span class="line"> <span class="attr">attachments</span>: […], <span class="comment">// <- 如果有附件也一并塞</span></span><br><span class="line"> },</span><br><span class="line"> { <span class="attr">attempts</span>: <span class="number">3</span>, <span class="attr">backoff</span>: { <span class="attr">type</span>: <span class="string">'fixed'</span>, <span class="attr">delay</span>: <span class="number">5_000</span> } },</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line"><span class="comment">// process 里只关注发送</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">async</span> <span class="title function_">process</span>(<span class="params"><span class="attr">job</span>: <span class="title class_">Job</span></span>) {</span><br><span class="line"> <span class="keyword">try</span> {</span><br><span class="line"> <span class="keyword">await</span> <span class="variable language_">this</span>.<span class="property">mailService</span>.<span class="title function_">send</span>({</span><br><span class="line"> <span class="attr">to</span>: job.<span class="property">data</span>.<span class="property">mail</span>.<span class="property">to</span>,</span><br><span class="line"> <span class="attr">subject</span>: <span class="string">`系统 24h 报表`</span>,</span><br><span class="line"> <span class="attr">html</span>: job.<span class="property">data</span>.<span class="property">reportHtml</span>,</span><br><span class="line"> <span class="attr">attachments</span>: job.<span class="property">data</span>.<span class="property">attachments</span>,</span><br><span class="line"> });</span><br><span class="line"> } <span class="keyword">catch</span> (e) {</span><br><span class="line"> <span class="keyword">throw</span> e; <span class="comment">// 触发重试</span></span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure><br> ➜ 重试带来的任何延迟,都不影响邮件正文,始终是一份「事先约定好、并且静态化」的报告。</p> -<p>这两种模式都能保证最终发送时的数据窗口或内容,与当初调度时的预期完全一致,不会因为重试延迟而出现“数据真空”或“多算/少算”问题。</p> -<h2 id="参考文档:"><a href="#参考文档:" class="headerlink" title="参考文档:"></a>参考文档:</h2><ul> -<li>“Retrying failing jobs” · BullMQ Guide<br><a href="https://docs.bullmq.io/guide/retrying-failing-jobs">https://docs.bullmq.io/guide/retrying-failing-jobs</a></li> -<li>BullMQ Guide & Patterns · Process Step Jobs (completed event only fires after process resolves)<br><a href="https://docs.bullmq.io/patterns/process-step-jobs">https://docs.bullmq.io/patterns/process-step-jobs</a></li> +<p>➜ 这样无是马上执行还是几次重试后才执行,数据规则都不会变。</p> +<p>二、预先生成「静态报表内容」,挂到队列里<br> +如果计算成本很高,或者怕重复查询数据开销大,也可以在调度时就把最终的 HTML/Text/附件 都先打好,然后作为 <code>job.data</code> 传进去,真正的 <code>process()</code> 只做一次“发送”即可:</p> + <figure class="highlight ts"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 调度时:先生成报告</span></span><br><span class="line"><span class="keyword">const</span> now = <span class="keyword">new</span> <span class="title class_">Date</span>();</span><br><span class="line"><span class="keyword">const</span> windowStart = <span class="keyword">new</span> <span class="title class_">Date</span>(now.<span class="title function_">getTime</span>() - <span class="number">24</span>*<span class="number">3600</span>*<span class="number">1000</span>);</span><br><span class="line"><span class="keyword">const</span> events = <span class="keyword">await</span> <span class="variable language_">this</span>.<span class="property">reportService</span>.<span class="title function_">findEvents</span>(windowStart, now);</span><br><span class="line"><span class="keyword">const</span> reportHtml = <span class="keyword">await</span> <span class="variable language_">this</span>.<span class="property">reportService</span>.<span class="title function_">renderReport</span>(events);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 把静态内容塞到队列</span></span><br><span class="line"><span class="keyword">await</span> <span class="variable language_">this</span>.<span class="property">mailerQueue</span>.<span class="title function_">add</span>(</span><br><span class="line"> id,</span><br><span class="line"> {</span><br><span class="line"> <span class="attr">mail</span>: <span class="keyword">new</span> <span class="title class_">Mail</span>({ <span class="comment">/*…*/</span>, windowStart, <span class="attr">windowEnd</span>: now }),</span><br><span class="line"> reportHtml, <span class="comment">// <- 预渲染好的文本/HTML</span></span><br><span class="line"> <span class="attr">attachments</span>: […], <span class="comment">// <- 如果有附件也一并塞</span></span><br><span class="line"> },</span><br><span class="line"> { <span class="attr">attempts</span>: <span class="number">3</span>, <span class="attr">backoff</span>: { <span class="attr">type</span>: <span class="string">'fixed'</span>, <span class="attr">delay</span>: <span class="number">5_000</span> } },</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line"><span class="comment">// process 里只关注发送</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">async</span> <span class="title function_">process</span>(<span class="params"><span class="attr">job</span>: <span class="title class_">Job</span></span>) {</span><br><span class="line"> <span class="keyword">try</span> {</span><br><span class="line"> <span class="keyword">await</span> <span class="variable language_">this</span>.<span class="property">mailService</span>.<span class="title function_">send</span>({</span><br><span class="line"> <span class="attr">to</span>: job.<span class="property">data</span>.<span class="property">mail</span>.<span class="property">to</span>,</span><br><span class="line"> <span class="attr">subject</span>: <span class="string">`系统 24h 报表`</span>,</span><br><span class="line"> <span class="attr">html</span>: job.<span class="property">data</span>.<span class="property">reportHtml</span>,</span><br><span class="line"> <span class="attr">attachments</span>: job.<span class="property">data</span>.<span class="property">attachments</span>,</span><br><span class="line"> });</span><br><span class="line"> } <span class="keyword">catch</span> (e) {</span><br><span class="line"> <span class="keyword">throw</span> e; <span class="comment">// 触发重试</span></span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure> +<p>➜ 重试带来的任何延迟,都不影响邮件正文,始终是一份「事先约定好、并且静态化」的报告。</p> +<p>这两种模式都能保证最终发送时的数据窗口或内容,与当初调度时的预期完全一致,不会因为重试延迟而出现“数据真空”或“多算/少算”问题。</p> +<h2 id="参考文档:"><a class="header-anchor" href="#参考文档:">¶</a>参考文档:</h2> +<ul> +<li>“Retrying failing jobs” · BullMQ Guide<br> +<a href="https://docs.bullmq.io/guide/retrying-failing-jobs">https://docs.bullmq.io/guide/retrying-failing-jobs</a></li> +<li>BullMQ Guide & Patterns · Process Step Jobs (completed event only fires after process resolves)<br> +<a href="https://docs.bullmq.io/patterns/process-step-jobs">https://docs.bullmq.io/patterns/process-step-jobs</a></li> </ul> ]]></content> <tags> @@ -2802,20 +3080,19 @@ await prisma.$transaction(async tx => { <title>NestJS 中 enableImplicitConversion 与 @Transform 的冲突</title> <url>/2025/08/13/nestjs-enableImplicitConversion-and-transform/</url> <content><![CDATA[<p>在 NestJS 生态中,<code>class-validator</code> 和 <code>class-transformer</code> 这两个库提供了以声明式的方式对 DTO 进行验证和转换。然而在处理布尔值时,如果在全局验证管道或仅仅是在局部同时开启了 <code>enableImplicitConversion</code>,可能会引入一个极其隐蔽且违反直觉的 Bug:前端传过来的布尔值恒为 true。</p> -<h2 id="一个简单的筛选功能"><a href="#一个简单的筛选功能" class="headerlink" title="一个简单的筛选功能"></a>一个简单的筛选功能</h2><p>假设正在开发一个电子商务平台的 API,需要实现一个产品列表的筛选功能。希望能够根据产品是否有库存 (<code>hasStock</code>)、是否为特色产品 (<code>isFeatured</code>) 等布尔条件进行筛选。</p> +<h2 id="一个简单的筛选功能"><a class="header-anchor" href="#一个简单的筛选功能">¶</a>一个简单的筛选功能</h2> +<p>假设正在开发一个电子商务平台的 API,需要实现一个产品列表的筛选功能。希望能够根据产品是否有库存 (<code>hasStock</code>)、是否为特色产品 (<code>isFeatured</code>) 等布尔条件进行筛选。</p> <p>前端发出的请求 URL 可能如下所示: <code>/products?filter[hasStock]=true&filter[isFeatured]=false</code></p> <p>在 NestJS 后端,首先会在 <code>main.ts</code> 中配置一个全局的 <code>ValidationPipe</code>,以自动处理 DTO 的验证和转换。为了方便,通常会启用 <code>enableImplicitConversion</code>,期望它能自动将 URL 查询参数中的字符串(如 <code>"123"</code>, <code>"true"</code>)转换为 DTO 中定义的类型(<code>number</code>, <code>boolean</code>):</p> <figure class="highlight typescript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// main.ts</span></span><br><span class="line"><span class="keyword">import</span> { <span class="title class_">ValidationPipe</span> } <span class="keyword">from</span> <span class="string">'@nestjs/common'</span>;</span><br><span class="line"><span class="keyword">import</span> { <span class="title class_">NestFactory</span> } <span class="keyword">from</span> <span class="string">'@nestjs/core'</span>;</span><br><span class="line"><span class="keyword">import</span> { <span class="title class_">AppModule</span> } <span class="keyword">from</span> <span class="string">'./app.module'</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">async</span> <span class="keyword">function</span> <span class="title function_">bootstrap</span>(<span class="params"></span>) {</span><br><span class="line"> <span class="keyword">const</span> app = <span class="keyword">await</span> <span class="title class_">NestFactory</span>.<span class="title function_">create</span>(<span class="title class_">AppModule</span>);</span><br><span class="line"></span><br><span class="line"> app.<span class="title function_">useGlobalPipes</span>(</span><br><span class="line"> <span class="keyword">new</span> <span class="title class_">ValidationPipe</span>({</span><br><span class="line"> <span class="attr">transform</span>: <span class="literal">true</span>, <span class="comment">// 启用转换</span></span><br><span class="line"> <span class="attr">whitelist</span>: <span class="literal">true</span>,</span><br><span class="line"> <span class="attr">forbidNonWhitelisted</span>: <span class="literal">true</span>,</span><br><span class="line"> <span class="attr">transformOptions</span>: {</span><br><span class="line"> <span class="comment">// 启用基于 TypeScript 类型的隐式转换</span></span><br><span class="line"> <span class="attr">enableImplicitConversion</span>: <span class="literal">true</span>, </span><br><span class="line"> },</span><br><span class="line"> }),</span><br><span class="line"> );</span><br><span class="line"> </span><br><span class="line"> <span class="comment">// ... 其他配置</span></span><br><span class="line"> <span class="keyword">await</span> app.<span class="title function_">listen</span>(<span class="number">3000</span>);</span><br><span class="line">}</span><br><span class="line"><span class="title function_">bootstrap</span>();</span><br></pre></td></tr></table></figure> - <p>接着,定义一个 <code>ProductFilterDto</code> 来接收这些筛选条件。</p> <p><strong>一个看似正确的 DTO 定义:</strong></p> <figure class="highlight typescript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// product-filter.dto.ts</span></span><br><span class="line"><span class="keyword">import</span> { <span class="title class_">IsBoolean</span>, <span class="title class_">IsOptional</span> } <span class="keyword">from</span> <span class="string">'class-validator'</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">class</span> <span class="title class_">ProductFilterDto</span> {</span><br><span class="line"> <span class="meta">@IsOptional</span>()</span><br><span class="line"> <span class="meta">@IsBoolean</span>()</span><br><span class="line"> <span class="attr">hasStock</span>?: <span class="built_in">boolean</span>;</span><br><span class="line"></span><br><span class="line"> <span class="meta">@IsOptional</span>()</span><br><span class="line"> <span class="meta">@IsBoolean</span>()</span><br><span class="line"> <span class="attr">isFeatured</span>?: <span class="built_in">boolean</span>;</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - <p>在控制器中使用这个 DTO:</p> <figure class="highlight typescript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// products.controller.ts</span></span><br><span class="line"><span class="meta">@Controller</span>(<span class="string">'products'</span>)</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">class</span> <span class="title class_">ProductsController</span> {</span><br><span class="line"> <span class="meta">@Get</span>()</span><br><span class="line"> <span class="title function_">find</span>(<span class="params"><span class="meta">@Query</span>(<span class="string">'filter'</span>) <span class="attr">filter</span>: <span class="title class_">ProductFilterDto</span></span>) {</span><br><span class="line"> <span class="comment">// 期望 filter.isFeatured 的值为 boolean false</span></span><br><span class="line"> <span class="variable language_">console</span>.<span class="title function_">log</span>(filter); </span><br><span class="line"> <span class="comment">// ... 业务逻辑</span></span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - <p>当请求 <code>.../products?filter[isFeatured]=false</code> 到达时,本来期望在 <code>find</code> 方法中得到的 <code>filter.isFeatured</code> 的值是布尔类型的 <code>false</code>。然而,控制台输出的结果却令人意外:<code>{ isFeatured: true }</code></p> -<h2 id="问题剖析"><a href="#问题剖析" class="headerlink" title="问题剖析"></a>问题剖析</h2><p>这个问题的根源在于 <code>class-transformer</code> 内部的转换执行顺序,以及 JavaScript 中 <code>Boolean</code> 函数的类型转换行为。</p> +<h2 id="问题剖析"><a class="header-anchor" href="#问题剖析">¶</a>问题剖析</h2> +<p>这个问题的根源在于 <code>class-transformer</code> 内部的转换执行顺序,以及 JavaScript 中 <code>Boolean</code> 函数的类型转换行为。</p> <p>所有通过 URL 查询参数传递的值,其本质都是字符串。当 NestJS 接收到请求时,<code>filter.isFeatured</code> 的原始值是字符串 <code>"false"</code>。</p> <p><code>ValidationPipe</code> 启动 <code>class-transformer</code> 的转换流程。由于在全局管道中设置了 <code>enableImplicitConversion: true</code>,转换器会首先检查 DTO 属性的 TypeScript 类型。</p> <ol> @@ -2826,21 +3103,19 @@ await prisma.$transaction(async tx => { <p>此时,即使尝试添加一个自定义的 <code>@Transform</code> 装饰器来手动处理这个问题,也为时已晚。</p> <p>例如,定义一个 <code>booleanTransformer</code>:</p> <figure class="highlight typescript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// boolean-transformer.ts</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> <span class="title function_">booleanTransformer</span> = (<span class="params">{ value }: { value: <span class="built_in">any</span> }</span>) => {</span><br><span class="line"> <span class="keyword">if</span> (<span class="keyword">typeof</span> value === <span class="string">'string'</span>) {</span><br><span class="line"> <span class="keyword">return</span> value === <span class="string">'true'</span>;</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">return</span> value;</span><br><span class="line">};</span><br></pre></td></tr></table></figure> - <p>然后更新 dto:</p> <figure class="highlight typescript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// product-filter.dto.ts (错误的尝试)</span></span><br><span class="line"><span class="keyword">import</span> { <span class="title class_">Transform</span> } <span class="keyword">from</span> <span class="string">'class-transformer'</span>;</span><br><span class="line"><span class="keyword">import</span> { <span class="title class_">IsBoolean</span>, <span class="title class_">IsOptional</span> } <span class="keyword">from</span> <span class="string">'class-validator'</span>;</span><br><span class="line"><span class="keyword">import</span> { booleanTransformer } <span class="keyword">from</span> <span class="string">'./boolean-transformer'</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">class</span> <span class="title class_">ProductFilterDto</span> {</span><br><span class="line"> <span class="comment">// ...</span></span><br><span class="line"> <span class="meta">@IsOptional</span>()</span><br><span class="line"> <span class="meta">@Transform</span>(booleanTransformer) <span class="comment">// 添加自定义转换</span></span><br><span class="line"> <span class="meta">@IsBoolean</span>()</span><br><span class="line"> <span class="attr">isFeatured</span>?: <span class="built_in">boolean</span>;</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - <p>流程会变成这样:</p> <ol> <li>隐式转换首先执行:<code>Boolean("false")</code> -> <code>true</code>。</li> <li><code>@Transform</code> 装饰器执行:此时传递给 <code>booleanTransformer</code> 的 <code>value</code> 已经是上一步错误转换后的布尔值 <code>true</code>,而不是原始的字符串 <code>"false"</code>。转换函数无从下手。</li> </ol> <p>最终结果依然是 <code>true</code>。</p> -<h2 id="解决方案:用-any-绕过隐式转换"><a href="#解决方案:用-any-绕过隐式转换" class="headerlink" title="## 解决方案:用 any 绕过隐式转换"></a>## 解决方案:用 <code>any</code> 绕过隐式转换</h2><p>要解决这个问题,核心在于阻止 <code>class-transformer</code> 进行那次错误的、优先的隐式转换,从而确保自定义 <code>@Transform</code> 函数能接收到最原始的字符串值。</p> +<h2 id="解决方案:用-any-绕过隐式转换"><a class="header-anchor" href="#解决方案:用-any-绕过隐式转换">¶</a>## 解决方案:用 <code>any</code> 绕过隐式转换</h2> +<p>要解决这个问题,核心在于阻止 <code>class-transformer</code> 进行那次错误的、优先的隐式转换,从而确保自定义 <code>@Transform</code> 函数能接收到最原始的字符串值。</p> <p>最直接且侵入性最小的方法,是将 DTO 中相关属性的 TypeScript 类型从 <code>boolean</code> 改为 <code>any</code>。</p> <p><strong>修正后的 DTO 定义:</strong></p> <figure class="highlight typescript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// product-filter.dto.ts (正确的实现)</span></span><br><span class="line"><span class="keyword">import</span> { <span class="title class_">Transform</span> } <span class="keyword">from</span> <span class="string">'class-transformer'</span>;</span><br><span class="line"><span class="keyword">import</span> { <span class="title class_">IsBoolean</span>, <span class="title class_">IsOptional</span> } <span class="keyword">from</span> <span class="string">'class-validator'</span>;</span><br><span class="line"><span class="keyword">import</span> { booleanTransformer } <span class="keyword">from</span> <span class="string">'./boolean-transformer'</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 一个更健壮的 booleanTransformer</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> <span class="title function_">robustBooleanTransformer</span> = (<span class="params">{ value }: { value: <span class="built_in">string</span> }</span>) =></span><br><span class="line"> value === <span class="string">'true'</span> ? <span class="literal">true</span> : value === <span class="string">'false'</span> ? <span class="literal">false</span> : value;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">class</span> <span class="title class_">ProductFilterDto</span> {</span><br><span class="line"> <span class="meta">@IsOptional</span>()</span><br><span class="line"> <span class="meta">@Transform</span>(robustBooleanTransformer)</span><br><span class="line"> <span class="meta">@IsBoolean</span>()</span><br><span class="line"> <span class="attr">hasStock</span>?: <span class="built_in">any</span>; <span class="comment">// <-- 类型从 boolean 改为 any</span></span><br><span class="line"></span><br><span class="line"> <span class="meta">@IsOptional</span>()</span><br><span class="line"> <span class="meta">@Transform</span>(robustBooleanTransformer)</span><br><span class="line"> <span class="meta">@IsBoolean</span>()</span><br><span class="line"> <span class="attr">isFeatured</span>?: <span class="built_in">any</span>; <span class="comment">// <-- 类型从 boolean 改为 any</span></span><br><span class="line">}</span><br></pre></td></tr></table></figure> - <p>这个改动虽然看起来放弃了 TypeScript 的类型检查,但在这个特定的场景下,它非常安全且有效。原因如下:</p> <ol> <li><strong>阻止隐式转换</strong>:当 <code>class-transformer</code> 看到属性类型是 <code>any</code> 时,它不知道该隐式转换成什么目标类型,因此会“跳过”这个属性的隐式转换步骤。</li> @@ -2857,40 +3132,50 @@ await prisma.$transaction(async tx => { <title>NestJS 嵌套查询参数解析错误分析与解决方案</title> <url>/2025/07/29/nestjs-nested-object-dto/</url> <content><![CDATA[<p>在开发 NestJS 应用程序时,一个常见的场景是根据复杂的条件筛选资源。当使用嵌套查询参数来表达这些条件时,例如通过 URL <code>http://localhost:3000/products/filter?filters[price][min]=100</code>,可能会意外地遇到 <code>property filters[price][min] should not exist</code> 错误。本文将深入剖析此问题背后的原因,并提供针对 Express 和 Fastify 两种底层框架的解决方案。</p> -<h4 id="问题背景"><a href="#问题背景" class="headerlink" title="问题背景"></a>问题背景</h4><p>假设我们正在构建一个电子商务平台的后端,需要实现一个商品筛选接口 <code>/products/filter</code>。该接口应允许客户端根据不同的属性(如价格 <code>price</code>、库存 <code>stock</code>)进行筛选,并支持对数值型属性(如价格)指定一个范围。</p> +<h4 id="问题背景"><a class="header-anchor" href="#问题背景">¶</a>问题背景</h4> +<p>假设我们正在构建一个电子商务平台的后端,需要实现一个商品筛选接口 <code>/products/filter</code>。该接口应允许客户端根据不同的属性(如价格 <code>price</code>、库存 <code>stock</code>)进行筛选,并支持对数值型属性(如价格)指定一个范围。</p> <p>为了实现这一功能,我们定义了以下 NestJS 数据传输对象 (DTO) 结构:</p> <figure class="highlight typescript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> { <span class="title class_">ApiPropertyOptional</span> } <span class="keyword">from</span> <span class="string">"@nestjs/swagger"</span>;</span><br><span class="line"><span class="keyword">import</span> {</span><br><span class="line"> <span class="title class_">IsNumber</span>,</span><br><span class="line"> <span class="title class_">IsOptional</span>,</span><br><span class="line"> <span class="title class_">Min</span>,</span><br><span class="line"> <span class="title class_">ValidateNested</span>,</span><br><span class="line">} <span class="keyword">from</span> <span class="string">"class-validator"</span>;</span><br><span class="line"><span class="keyword">import</span> { <span class="title class_">Type</span> } <span class="keyword">from</span> <span class="string">"class-transformer"</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">RangeFilterDto</span> {</span><br><span class="line"> <span class="meta">@ApiPropertyOptional</span>({ <span class="attr">description</span>: <span class="string">"最小值 (大于等于)"</span> })</span><br><span class="line"> <span class="meta">@IsOptional</span>()</span><br><span class="line"> <span class="meta">@Type</span>(<span class="function">() =></span> <span class="title class_">Number</span>)</span><br><span class="line"> <span class="meta">@IsNumber</span>()</span><br><span class="line"> <span class="meta">@Min</span>(<span class="number">0</span>)</span><br><span class="line"> <span class="attr">min</span>?: <span class="built_in">number</span>;</span><br><span class="line"></span><br><span class="line"> <span class="meta">@ApiPropertyOptional</span>({ <span class="attr">description</span>: <span class="string">"最大值 (小于等于)"</span> })</span><br><span class="line"> <span class="meta">@IsOptional</span>()</span><br><span class="line"> <span class="meta">@Type</span>(<span class="function">() =></span> <span class="title class_">Number</span>)</span><br><span class="line"> <span class="meta">@IsNumber</span>()</span><br><span class="line"> <span class="meta">@Min</span>(<span class="number">0</span>)</span><br><span class="line"> <span class="attr">max</span>?: <span class="built_in">number</span>;</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">ProductAttributeFilterDto</span> {</span><br><span class="line"> <span class="meta">@ApiPropertyOptional</span>({</span><br><span class="line"> <span class="attr">description</span>: <span class="string">"价格范围"</span>,</span><br><span class="line"> <span class="attr">type</span>: <span class="title class_">RangeFilterDto</span>,</span><br><span class="line"> })</span><br><span class="line"> <span class="meta">@IsOptional</span>()</span><br><span class="line"> <span class="meta">@ValidateNested</span>()</span><br><span class="line"> <span class="meta">@Type</span>(<span class="function">() =></span> <span class="title class_">RangeFilterDto</span>)</span><br><span class="line"> <span class="attr">price</span>?: <span class="title class_">RangeFilterDto</span>;</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">class</span> <span class="title class_">ProductFilterDto</span> {</span><br><span class="line"> <span class="meta">@ApiPropertyOptional</span>({ <span class="attr">description</span>: <span class="string">"商品属性筛选条件"</span> })</span><br><span class="line"> <span class="meta">@IsOptional</span>()</span><br><span class="line"> <span class="meta">@ValidateNested</span>()</span><br><span class="line"> <span class="meta">@Type</span>(<span class="function">() =></span> <span class="title class_">ProductAttributeFilterDto</span>)</span><br><span class="line"> <span class="attr">filters</span>?: <span class="title class_">ProductAttributeFilterDto</span>;</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - <p>对应的控制器代码如下:</p> <figure class="highlight typescript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> { <span class="title class_">Controller</span>, <span class="title class_">Get</span>, <span class="title class_">Query</span> } <span class="keyword">from</span> <span class="string">'@nestjs/common'</span>;</span><br><span class="line"><span class="keyword">import</span> { <span class="title class_">ApiOperation</span>, <span class="title class_">ApiResponse</span>, <span class="title class_">ApiTags</span> } <span class="keyword">from</span> <span class="string">'@nestjs/swagger'</span>;</span><br><span class="line"><span class="keyword">import</span> { <span class="title class_">ProductFilterDto</span> } <span class="keyword">from</span> <span class="string">'./dtos/product-filter.dto'</span>;</span><br><span class="line"></span><br><span class="line"><span class="meta">@ApiTags</span>(<span class="string">'products'</span>)</span><br><span class="line"><span class="meta">@Controller</span>(<span class="string">'products'</span>)</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">class</span> <span class="title class_">ProductsController</span> {</span><br><span class="line"> <span class="meta">@Get</span>(<span class="string">"filter"</span>)</span><br><span class="line"> <span class="meta">@ApiOperation</span>({ <span class="attr">summary</span>: <span class="string">"根据条件筛选商品"</span> })</span><br><span class="line"> <span class="meta">@ApiResponse</span>({ <span class="attr">status</span>: <span class="number">200</span>, <span class="attr">description</span>: <span class="string">"筛选商品成功"</span> })</span><br><span class="line"> <span class="meta">@ApiResponse</span>({ <span class="attr">status</span>: <span class="number">400</span>, <span class="attr">description</span>: <span class="string">"请求参数错误"</span> })</span><br><span class="line"> <span class="keyword">async</span> <span class="title function_">getFilteredProducts</span>(</span><br><span class="line"> <span class="meta">@Query</span>() <span class="attr">query</span>: <span class="title class_">ProductFilterDto</span>,</span><br><span class="line"> ): <span class="title class_">Promise</span><<span class="built_in">any</span>> {</span><br><span class="line"> <span class="comment">// 在实际应用中,这里会调用服务处理筛选逻辑</span></span><br><span class="line"> <span class="variable language_">console</span>.<span class="title function_">log</span>(query);</span><br><span class="line"> <span class="keyword">return</span> {</span><br><span class="line"> <span class="attr">message</span>: <span class="string">"Products filtered successfully."</span>,</span><br><span class="line"> <span class="attr">data</span>: query,</span><br><span class="line"> };</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - <p>当客户端通过以下 URL 发送请求时:</p> <p><code>http://localhost:3000/products/filter?filters[price][min]=100</code></p> <p>后端返回了 HTTP 400 错误,并附带以下日志:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">[Nest] 12345 - 07/29/2025, 11:00:00 AM ERROR [HttpExceptionFilter] [GET /products/filter?filters%5Bprice%5D%5Bmin%5D=100] HTTP 400 Error: property filters[price][min] should not exist</span><br><span class="line">BadRequestException: Bad Request Exception</span><br><span class="line"> at ValidationPipe.exceptionFactory (/path/to/project/node_modules/@nestjs/common/pipes/validation.pipe.js:107:20)</span><br><span class="line"> at ValidationPipe.transform (/path/to/project/node_modules/@nestjs/common/pipes/validation.pipe.js:74:30)</span><br><span class="line"> ... (其他堆栈信息)</span><br></pre></td></tr></table></figure> - -<h4 id="错误分析"><a href="#错误分析" class="headerlink" title="错误分析"></a>错误分析</h4><p>此错误的核心在于 NestJS 的 <code>@Query()</code> 装饰器与 <code>ValidationPipe</code> 在处理 URL 查询字符串时的默认行为,未能正确地将客户端提供的嵌套方括号语法 (<code>filters[price][min]</code>) 解析为 DTO 所期望的 JavaScript 嵌套对象结构。</p> +<h4 id="错误分析"><a class="header-anchor" href="#错误分析">¶</a>错误分析</h4> +<p>此错误的核心在于 NestJS 的 <code>@Query()</code> 装饰器与 <code>ValidationPipe</code> 在处理 URL 查询字符串时的默认行为,未能正确地将客户端提供的嵌套方括号语法 (<code>filters[price][min]</code>) 解析为 DTO 所期望的 JavaScript 嵌套对象结构。</p> <ol> -<li><p><strong>DTO 的预期结构:</strong><br><code>ProductFilterDto</code> 定义了 <code>filters</code> 属性,其类型为 <code>ProductAttributeFilterDto</code>。<code>ProductAttributeFilterDto</code> 又包含了 <code>price</code> 属性,类型为 <code>RangeFilterDto</code>,最终含有 <code>min</code> 和 <code>max</code> 属性。这意味着 DTO 期望接收的数据结构应为:<code>{ filters: { price: { min: 100 } } }</code>。</p> +<li> +<p><strong>DTO 的预期结构:</strong><br> +<code>ProductFilterDto</code> 定义了 <code>filters</code> 属性,其类型为 <code>ProductAttributeFilterDto</code>。<code>ProductAttributeFilterDto</code> 又包含了 <code>price</code> 属性,类型为 <code>RangeFilterDto</code>,最终含有 <code>min</code> 和 <code>max</code> 属性。这意味着 DTO 期望接收的数据结构应为:<code>{ filters: { price: { min: 100 } } }</code>。</p> </li> -<li><p><strong>URL 查询参数的扁平化解析:</strong><br>HTTP 协议的查询字符串本质上是扁平的键值对集合。虽然 <code>key[nestedKey]=value</code> 这种方括号语法被许多 Web 框架(如 PHP、Ruby on Rails)和库(如 <code>qs</code>)广泛用于表示嵌套数据,但这并非 HTTP 协议的标准。<br>NestJS 依赖其底层 HTTP 适配器(默认为 Express)来解析传入的请求。在默认配置下,Express 不会自动地、递归地将 <code>filters[price][min]</code> 这样的字符串键名解析成一个具有正确嵌套层级的 JavaScript 对象。相反,它会将其视为一个完整的、扁平的字符串键名 <code>filters[price][min]</code>,并将其值 <code>100</code> 与之对应。</p> +<li> +<p><strong>URL 查询参数的扁平化解析:</strong><br> +HTTP 协议的查询字符串本质上是扁平的键值对集合。虽然 <code>key[nestedKey]=value</code> 这种方括号语法被许多 Web 框架(如 PHP、Ruby on Rails)和库(如 <code>qs</code>)广泛用于表示嵌套数据,但这并非 HTTP 协议的标准。<br> +NestJS 依赖其底层 HTTP 适配器(默认为 Express)来解析传入的请求。在默认配置下,Express 不会自动地、递归地将 <code>filters[price][min]</code> 这样的字符串键名解析成一个具有正确嵌套层级的 JavaScript 对象。相反,它会将其视为一个完整的、扁平的字符串键名 <code>filters[price][min]</code>,并将其值 <code>100</code> 与之对应。</p> </li> -<li><p><strong><code>ValidationPipe</code> 的验证失败:</strong><br>当 <code>ValidationPipe</code> 接收到被扁平化解析后的查询参数时,它会在 <code>ProductFilterDto</code> 中寻找一个名为 <code>filters[price][min]</code> 的顶层属性。由于 DTO 中并未直接定义这样一个扁平的属性,并且 <code>ValidationPipe</code> 通常会启用 <code>forbidNonWhitelisted: true</code> 或 <code>whitelist: true</code> 选项来拒绝 DTO 中未明确声明的属性,因此验证过程失败,并抛出 <code>property filters[price][min] should not exist</code> 的错误。这表明 <code>ValidationPipe</code> 将 <code>filters[price][min]</code> 视为一个非法的、未在白名单中的属性,而不是预期的嵌套对象 <code>filters</code> 下的深层子属性。</p> +<li> +<p><strong><code>ValidationPipe</code> 的验证失败:</strong><br> +当 <code>ValidationPipe</code> 接收到被扁平化解析后的查询参数时,它会在 <code>ProductFilterDto</code> 中寻找一个名为 <code>filters[price][min]</code> 的顶层属性。由于 DTO 中并未直接定义这样一个扁平的属性,并且 <code>ValidationPipe</code> 通常会启用 <code>forbidNonWhitelisted: true</code> 或 <code>whitelist: true</code> 选项来拒绝 DTO 中未明确声明的属性,因此验证过程失败,并抛出 <code>property filters[price][min] should not exist</code> 的错误。这表明 <code>ValidationPipe</code> 将 <code>filters[price][min]</code> 视为一个非法的、未在白名单中的属性,而不是预期的嵌套对象 <code>filters</code> 下的深层子属性。</p> </li> </ol> <p>简而言之,问题不在于 DTO 定义或 <code>@Query()</code> 装饰器本身,而在于底层 HTTP 框架对查询字符串的默认解析行为与 NestJS <code>ValidationPipe</code> 对复杂嵌套 DTO 结构的需求不匹配。</p> -<h4 id="解决方案"><a href="#解决方案" class="headerlink" title="解决方案"></a>解决方案</h4><p>要解决此问题,关键在于配置 NestJS 应用的底层 HTTP 适配器,使其能够正确地解析包含方括号语法的嵌套查询参数,将其转换为嵌套的 JavaScript 对象。</p> -<h5 id="针对-Express-适配器"><a href="#针对-Express-适配器" class="headerlink" title="针对 Express 适配器"></a>针对 Express 适配器</h5><p>如果您的 NestJS 应用使用 Express 作为底层 HTTP 框架(这是新项目的默认配置),您需要在应用的入口文件(通常是 <code>main.ts</code>)中,通过 <code>app.set('query parser', 'extended');</code> 显式启用 Express 的扩展查询字符串解析功能。此配置会指示 Express 使用 <code>qs</code> 库(Express 内置依赖)来处理查询字符串,该库能够正确处理嵌套结构。</p> +<h4 id="解决方案"><a class="header-anchor" href="#解决方案">¶</a>解决方案</h4> +<p>要解决此问题,关键在于配置 NestJS 应用的底层 HTTP 适配器,使其能够正确地解析包含方括号语法的嵌套查询参数,将其转换为嵌套的 JavaScript 对象。</p> +<h5 id="针对-Express-适配器"><a class="header-anchor" href="#针对-Express-适配器">¶</a>针对 Express 适配器</h5> +<p>如果您的 NestJS 应用使用 Express 作为底层 HTTP 框架(这是新项目的默认配置),您需要在应用的入口文件(通常是 <code>main.ts</code>)中,通过 <code>app.set('query parser', 'extended');</code> 显式启用 Express 的扩展查询字符串解析功能。此配置会指示 Express 使用 <code>qs</code> 库(Express 内置依赖)来处理查询字符串,该库能够正确处理嵌套结构。</p> <p>示例 (<code>main.ts</code>):</p> <figure class="highlight typescript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> { <span class="title class_">NestFactory</span> } <span class="keyword">from</span> <span class="string">'@nestjs/core'</span>;</span><br><span class="line"><span class="keyword">import</span> { <span class="title class_">AppModule</span> } <span class="keyword">from</span> <span class="string">'./app.module'</span>;</span><br><span class="line"><span class="keyword">import</span> { <span class="title class_">ValidationPipe</span> } <span class="keyword">from</span> <span class="string">'@nestjs/common'</span>;</span><br><span class="line"><span class="keyword">import</span> { <span class="title class_">NestExpressApplication</span> } <span class="keyword">from</span> <span class="string">'@nestjs/platform-express'</span>; <span class="comment">// 导入此类型</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">async</span> <span class="keyword">function</span> <span class="title function_">bootstrap</span>(<span class="params"></span>) {</span><br><span class="line"> <span class="keyword">const</span> app = <span class="keyword">await</span> <span class="title class_">NestFactory</span>.<span class="property">create</span><<span class="title class_">NestExpressApplication</span>>(<span class="title class_">AppModule</span>);</span><br><span class="line"></span><br><span class="line"> <span class="comment">// 启用 Express 的扩展查询参数解析</span></span><br><span class="line"> <span class="comment">// 'simple' (默认) | 'extended'</span></span><br><span class="line"> app.<span class="title function_">set</span>(<span class="string">'query parser'</span>, <span class="string">'extended'</span>);</span><br><span class="line"></span><br><span class="line"> app.<span class="title function_">useGlobalPipes</span>(<span class="keyword">new</span> <span class="title class_">ValidationPipe</span>({</span><br><span class="line"> <span class="attr">whitelist</span>: <span class="literal">true</span>, <span class="comment">// 自动剥离 DTO 中未定义的属性</span></span><br><span class="line"> <span class="attr">forbidNonWhitelisted</span>: <span class="literal">true</span>, <span class="comment">// 如果传入 DTO 中未定义的属性,则抛出错误</span></span><br><span class="line"> <span class="attr">transform</span>: <span class="literal">true</span>, <span class="comment">// 自动将负载转换为 DTO 类的实例</span></span><br><span class="line"> <span class="attr">transformOptions</span>: {</span><br><span class="line"> <span class="attr">enableImplicitConversion</span>: <span class="literal">true</span>, <span class="comment">// 允许隐式类型转换,配合 @Type()</span></span><br><span class="line"> },</span><br><span class="line"> }));</span><br><span class="line"></span><br><span class="line"> <span class="comment">// ... 其他配置</span></span><br><span class="line"> <span class="keyword">await</span> app.<span class="title function_">listen</span>(<span class="number">3000</span>);</span><br><span class="line">}</span><br><span class="line"><span class="title function_">bootstrap</span>();</span><br></pre></td></tr></table></figure> - -<h5 id="针对-Fastify-适配器"><a href="#针对-Fastify-适配器" class="headerlink" title="针对 Fastify 适配器"></a>针对 Fastify 适配器</h5><p>如果您的 NestJS 应用使用 Fastify 作为底层 HTTP 框架,您需要在创建 Fastify 适配器实例时,通过 <code>querystringParser</code> 选项提供一个自定义的查询字符串解析函数。通常,我们会利用 <code>qs</code> 这样的成熟库来完成递归解析。</p> -<p>首先,确保已安装 <code>qs</code> 库及其类型定义:<br><code>npm install qs</code><br><code>npm install -D @types/qs</code></p> +<h5 id="针对-Fastify-适配器"><a class="header-anchor" href="#针对-Fastify-适配器">¶</a>针对 Fastify 适配器</h5> +<p>如果您的 NestJS 应用使用 Fastify 作为底层 HTTP 框架,您需要在创建 Fastify 适配器实例时,通过 <code>querystringParser</code> 选项提供一个自定义的查询字符串解析函数。通常,我们会利用 <code>qs</code> 这样的成熟库来完成递归解析。</p> +<p>首先,确保已安装 <code>qs</code> 库及其类型定义:<br> +<code>npm install qs</code><br> +<code>npm install -D @types/qs</code></p> <p>示例 (<code>main.ts</code>):</p> <figure class="highlight typescript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> { <span class="title class_">NestFactory</span> } <span class="keyword">from</span> <span class="string">'@nestjs/core'</span>;</span><br><span class="line"><span class="keyword">import</span> { <span class="title class_">AppModule</span> } <span class="keyword">from</span> <span class="string">'./app.module'</span>;</span><br><span class="line"><span class="keyword">import</span> { <span class="title class_">ValidationPipe</span> } <span class="keyword">from</span> <span class="string">'@nestjs/common'</span>;</span><br><span class="line"><span class="keyword">import</span> {</span><br><span class="line"> <span class="title class_">FastifyAdapter</span>,</span><br><span class="line"> <span class="title class_">NestFastifyApplication</span>,</span><br><span class="line">} <span class="keyword">from</span> <span class="string">'@nestjs/platform-fastify'</span>;</span><br><span class="line"><span class="keyword">import</span> * <span class="keyword">as</span> qs <span class="keyword">from</span> <span class="string">'qs'</span>; <span class="comment">// 引入 qs 库</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">async</span> <span class="keyword">function</span> <span class="title function_">bootstrap</span>(<span class="params"></span>) {</span><br><span class="line"> <span class="keyword">const</span> app = <span class="keyword">await</span> <span class="title class_">NestFactory</span>.<span class="property">create</span><<span class="title class_">NestFastifyApplication</span>>(</span><br><span class="line"> <span class="title class_">AppModule</span>,</span><br><span class="line"> <span class="keyword">new</span> <span class="title class_">FastifyAdapter</span>({</span><br><span class="line"> <span class="comment">// 配置 Fastify 的查询字符串解析器</span></span><br><span class="line"> <span class="attr">querystringParser</span>: <span class="function">(<span class="params">str</span>) =></span> qs.<span class="title function_">parse</span>(str),</span><br><span class="line"> }),</span><br><span class="line"> );</span><br><span class="line"></span><br><span class="line"> app.<span class="title function_">useGlobalPipes</span>(<span class="keyword">new</span> <span class="title class_">ValidationPipe</span>({</span><br><span class="line"> <span class="attr">whitelist</span>: <span class="literal">true</span>,</span><br><span class="line"> <span class="attr">forbidNonWhitelisted</span>: <span class="literal">true</span>,</span><br><span class="line"> <span class="attr">transform</span>: <span class="literal">true</span>,</span><br><span class="line"> <span class="attr">transformOptions</span>: {</span><br><span class="line"> <span class="attr">enableImplicitConversion</span>: <span class="literal">true</span>,</span><br><span class="line"> },</span><br><span class="line"> }));</span><br><span class="line"></span><br><span class="line"> <span class="comment">// ... 其他配置</span></span><br><span class="line"> <span class="keyword">await</span> app.<span class="title function_">listen</span>(<span class="number">3000</span>);</span><br><span class="line">}</span><br><span class="line"><span class="title function_">bootstrap</span>();</span><br></pre></td></tr></table></figure> - -<p>通过上述配置,无论是使用 Express 还是 Fastify,NestJS 应用都将能够正确地将 <code>?filters[price][min]=100</code> 解析为 <code>{ filters: { price: { min: '100' } } }</code>。随后,在 <code>ValidationPipe</code> 的 <code>transform</code> 阶段,<code>@Type(() => Number)</code> 装饰器会确保 <code>min</code> 的值从字符串 <code>'100'</code> 转换为数字 <code>100</code>,从而顺利通过验证并注入到控制器方法中。</p> -<h3 id="引用"><a href="#引用" class="headerlink" title="引用"></a>引用</h3><ul> +<p>通过上述配置,无论是使用 Express 还是 Fastify,NestJS 应用都将能够正确地将 <code>?filters[price][min]=100</code> 解析为 <code>{ filters: { price: { min: '100' } } }</code>。随后,在 <code>ValidationPipe</code> 的 <code>transform</code> 阶段,<code>@Type(() => Number)</code> 装饰器会确保 <code>min</code> 的值从字符串 <code>'100'</code> 转换为数字 <code>100</code>,从而顺利通过验证并注入到控制器方法中。</p> +<h3 id="引用"><a class="header-anchor" href="#引用">¶</a>引用</h3> +<ul> <li><a href="https://stackoverflow.com/questions/29960764/what-does-extended-mean-in-express-4-0">What does ‘extended’ mean in express 4.0? - Stack Overflow</a></li> <li><a href="https://expressjs.com/en/5x/api.html#app.set">Express 5.0 - API Reference (<code>app.set</code>)</a></li> </ul> @@ -2907,7 +3192,6 @@ await prisma.$transaction(async tx => { <p>OCaml 编译器提供了一个名为 <a href="https://github.com/ocaml/ocaml/pull/10462"><code>[@poll error]</code></a> 的annotation,可以在函数中使用它来确保该函数不包含safe point。</p> <p>所以通过使用 <code>[@poll error]</code> 就可以创建在Domain内原子性执行的函数,也就是说,基于此特性可以实现单个Domain内线程安全的数据结构,例如 thread-table 便是使用这个特性实现的 Hash Table。可以看看它的 add 函数的实现:</p> <figure class="highlight ocaml"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span>[@poll error] add_atomically t buckets n i before after =</span><br><span class="line"> t.rehash = <span class="number">0</span> && buckets == t.buckets</span><br><span class="line"> && before == <span class="type">Array</span>.unsafe_get buckets i</span><br><span class="line"> && <span class="keyword">begin</span></span><br><span class="line"> <span class="type">Array</span>.unsafe_set buckets i after;</span><br><span class="line"> <span class="keyword">let</span> length = t.length + <span class="number">1</span> <span class="keyword">in</span></span><br><span class="line"> t.length <- length;</span><br><span class="line"> <span class="keyword">if</span> n < length && n < max_buckets_div_2 <span class="keyword">then</span> t.rehash <- n * <span class="number">2</span>;</span><br><span class="line"> <span class="literal">true</span></span><br><span class="line"> <span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> <span class="keyword">rec</span> add t k' v' =</span><br><span class="line"> <span class="keyword">let</span> h = <span class="type">Mix</span>.<span class="built_in">int</span> k' <span class="keyword">in</span></span><br><span class="line"> maybe_rehash t;</span><br><span class="line"> <span class="keyword">let</span> buckets = t.buckets <span class="keyword">in</span></span><br><span class="line"> <span class="keyword">let</span> n = <span class="type">Array</span>.length buckets <span class="keyword">in</span></span><br><span class="line"> <span class="keyword">let</span> i = h <span class="keyword">land</span> (n - <span class="number">1</span>) <span class="keyword">in</span></span><br><span class="line"> <span class="keyword">let</span> before = <span class="type">Array</span>.unsafe_get buckets i <span class="keyword">in</span></span><br><span class="line"> <span class="keyword">let</span> after = <span class="type">Cons</span> (k', v', before) <span class="keyword">in</span></span><br><span class="line"> <span class="keyword">if</span> not (add_atomically t buckets n i before after) <span class="keyword">then</span> add t k' v'</span><br></pre></td></tr></table></figure> - <p>相比使用 Stdlib.Mutex,这种无锁实现会有更好的性能(特别是对于只读操作),并且还允许例如信号处理之类的上下文操作。</p> ]]></content> <tags> @@ -2926,27 +3210,31 @@ await prisma.$transaction(async tx => { <p><strong>除权 (Ex-rights):</strong> 如果公司不是派现金,而是送股票(比如“10送3股”),那么总股本会增加,每股代表的实际价值就被稀释了。<strong>“除权”就是调整股价,以反映这种股本增加带来的稀释效应。</strong></p> <p>现金分红主要是除息。</p> <p>在2025年7月14日这一天,该股票的开盘参考价会人为地向下调整。</p> -<p>如果在除息日前一天(假设是T日)持有这只股票,那么资产 = 股票市值 + 即将到手的现金分红。 到了除息日(T+1日,即7月14日),市场会重新定价。新的股价 = 原股价 - 每股分红。</p> +<p>如果在除息日前一天(假设是T日)持有这只股票,那么资产 = 股票市值 + 即将到手的现金分红。 到了除息日(T+1日,即7月14日),市场会重新定价。新的股价 = 原股价 - 每股分红。</p> <p><strong>所以,除权除息日,本质上是股价因分红派息而进行调整的日子。</strong> 股价会下跌,但这并不意味着亏钱,因为股价减少的部分,恰好等于即将收到的现金红利。总资产在理论上保持不变。</p> <p>不过 “除权除息日” 并不是钱到账的日子。这一天发生的是<strong>股价的调整</strong>,而不是现金的发放。</p> <p>完整的分红流程如下:</p> <ol> -<li>股权登记日 (Record Date) <ul> +<li>股权登记日 (Record Date) +<ul> <li>按照A股市场的惯例(T+1制度),<strong>除权除息日通常是股权登记日的下一个交易日。</strong></li> <li>因此,如果除权除息日是2025年7月14日(周一),那么<strong>股权登记日很可能就是前一个交易日,即2025年7月11日(周五)。</strong> (注:这需要以公司正式公告为准,但逻辑如此)。</li> <li><strong>所以必须在股权登记日当天收盘时持有该股票,才能拿到分红。</strong></li> </ul> </li> -<li>除权除息日 (Ex-Date) — 股价调整的日子<ul> +<li>除权除息日 (Ex-Date) — 股价调整的日子 +<ul> <li><strong>股价调整:</strong> 股票价格会下跌,反映红利已被剔除。</li> -<li><strong>权利分割:</strong><ul> +<li><strong>权利分割:</strong> +<ul> <li>如果在这一天<strong>买入</strong>这只股票,无法享受这次分红。因为买的是已经“打折”后的股票。</li> <li>如果在这一天<strong>卖出</strong>在登记日持有的股票,依然可以拿到分红!因为在登记日是股东。</li> </ul> </li> </ul> </li> -<li>派息日 (Payment Date) <ul> +<li>派息日 (Payment Date) +<ul> <li>现金红利会在这一天自动打入你的证券资金账户。</li> <li>派息日通常在除权除息日之后几天,有时甚至是同一天,但这需要看上市公司的具体安排和公告。</li> </ul> @@ -2974,41 +3262,47 @@ await prisma.$transaction(async tx => { <content><![CDATA[<p>在前端,一个常见的性能瓶颈是初始加载时请求了用户当前 viewpoint 之外的非必要数据。惰性加载(Lazy Loading)是一种关键策略,它将数据获取推迟到组件进入 viewpoint 时才执行。本文将阐述如何结合使用 Svelte 5、<code>@tanstack/svelte-query</code> 和 <code>runed.dev</code> 的 <code>useIntersectionObserver</code>,构建一个通用的、可复用的惰性加载组件。</p> <p><strong>核心依赖与环境</strong></p> <ul> -<li><p><strong>Svelte 5:</strong> 本实现依赖于 Svelte 5 的符文(Runes)特性,它提供了更精细、更直观的状态管理能力。</p> +<li> +<p><strong>Svelte 5:</strong> 本实现依赖于 Svelte 5 的符文(Runes)特性,它提供了更精细、更直观的状态管理能力。</p> </li> -<li><p><strong>@tanstack/svelte-query:</strong> TanStack Query 的 Svelte 适配版,用户获取数据。</p> +<li> +<p><strong>@tanstack/svelte-query:</strong> TanStack Query 的 Svelte 适配版,用户获取数据。</p> </li> -<li><p><strong>runed.dev:</strong> 一个提供多种 Svelte 5 实用工具的库,本文主要使用其 <code>useIntersectionObserver</code>。</p> +<li> +<p><strong>runed.dev:</strong> 一个提供多种 Svelte 5 实用工具的库,本文主要使用其 <code>useIntersectionObserver</code>。</p> </li> </ul> -<h4 id="设计哲学:分离关注点"><a href="#设计哲学:分离关注点" class="headerlink" title="设计哲学:分离关注点"></a><strong>设计哲学:分离关注点</strong></h4><p>该方案的核心思想是将“何时加载”与“如何加载”这两个关注点进行解耦。</p> +<h4 id="设计哲学:分离关注点"><a class="header-anchor" href="#设计哲学:分离关注点">¶</a><strong>设计哲学:分离关注点</strong></h4> +<p>该方案的核心思想是将“何时加载”与“如何加载”这两个关注点进行解耦。</p> <ol> -<li><p><strong>何时加载 (When to Load):</strong> 组件的可见性决定了数据加载的时机。我们利用 <code>Intersection Observer API</code> 来精确、高效地监听一个元素是否进入 viewpoint。<code>runed.dev</code> 库为此提供了名为 <code>useIntersectionObserver</code> 的便捷封装。</p> +<li> +<p><strong>何时加载 (When to Load):</strong> 组件的可见性决定了数据加载的时机。我们利用 <code>Intersection Observer API</code> 来精确、高效地监听一个元素是否进入 viewpoint。<code>runed.dev</code> 库为此提供了名为 <code>useIntersectionObserver</code> 的便捷封装。</p> </li> -<li><p><strong>如何加载 (How to Load):</strong> 数据获取、缓存、同步和状态管理的复杂性由 <code>@tanstack/svelte-query</code> (TanStack Query) 处理。它提供了一套强大的工具集来管理异步数据。</p> +<li> +<p><strong>如何加载 (How to Load):</strong> 数据获取、缓存、同步和状态管理的复杂性由 <code>@tanstack/svelte-query</code> (TanStack Query) 处理。它提供了一套强大的工具集来管理异步数据。</p> </li> </ol> <p>通过将这两者结合,可以创建一个名为 <code>LazyQuery</code> 的抽象组件。该组件内部处理可见性检测,并根据检测结果动态控制 TanStack Query 的执行,而将具体的查询逻辑(<code>queryFn</code>)和键(<code>queryKey</code>)完全交由使用者定义。</p> -<h4 id="LazyQuery-组件的实现"><a href="#LazyQuery-组件的实现" class="headerlink" title="LazyQuery 组件的实现"></a><code>LazyQuery</code> 组件的实现</h4><blockquote> +<h4 id="LazyQuery-组件的实现"><a class="header-anchor" href="#LazyQuery-组件的实现">¶</a><code>LazyQuery</code> 组件的实现</h4> +<blockquote> <p>目标:封装惰性加载逻辑,并向外暴露一个标准的 TanStack Query 接口。</p> </blockquote> <p>一、对组件的接口类型做如下定义:</p> <figure class="highlight typescript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="keyword">type</span> { <span class="title class_">CreateQueryOptions</span>, <span class="title class_">QueryKey</span> } <span class="keyword">from</span> <span class="string">'@tanstack/svelte-query'</span>;</span><br><span class="line"><span class="keyword">import</span> <span class="keyword">type</span> { <span class="title class_">Snippet</span> } <span class="keyword">from</span> <span class="string">'svelte'</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">Props</span><</span><br><span class="line"> <span class="title class_">TQueryFnData</span> = <span class="built_in">unknown</span>,</span><br><span class="line"> <span class="title class_">TError</span> = <span class="title class_">Error</span>,</span><br><span class="line"> <span class="title class_">TData</span> = <span class="title class_">TQueryFnData</span>,</span><br><span class="line"> <span class="title class_">TQueryKey</span> <span class="keyword">extends</span> <span class="title class_">QueryKey</span> = <span class="title class_">QueryKey</span></span><br><span class="line">> = {</span><br><span class="line"> <span class="comment">/// 一个标准的 TanStack Query 配置对象</span></span><br><span class="line"> <span class="attr">queryOptions</span>: <span class="title class_">CreateQueryOptions</span><<span class="title class_">TQueryFnData</span>, <span class="title class_">TError</span>, <span class="title class_">TData</span>, <span class="title class_">TQueryKey</span>>;</span><br><span class="line"></span><br><span class="line"> <span class="comment">/// Svelte 5 的 `Snippet` 类型,它允许父组件向子组件传递一段可执行的 UI 模板。</span></span><br><span class="line"> <span class="comment">/// 这个 `Snippet` 会接收到 `createQuery` 返回的完整查询对象 `query`,</span></span><br><span class="line"> <span class="comment">/// 从而可以访问 `data`, `isLoading`, `error` 等所有状态。</span></span><br><span class="line"> <span class="attr">children</span>: <span class="title class_">Snippet</span><{</span><br><span class="line"> <span class="attr">query</span>: <span class="title class_">ReturnType</span><<span class="keyword">typeof</span> createQuery<<span class="title class_">TQueryFnData</span>, <span class="title class_">TError</span>, <span class="title class_">TData</span>, <span class="title class_">TQueryKey</span>>>;</span><br><span class="line"> }>;</span><br><span class="line">};</span><br></pre></td></tr></table></figure> - <p>二、组件逻辑:</p> <figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag"><<span class="name">script</span> <span class="attr">lang</span>=<span class="string">"ts"</span>></span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript"> <span class="keyword">import</span> { createQuery, type <span class="title class_">CreateQueryOptions</span>, type <span class="title class_">QueryKey</span> } <span class="keyword">from</span> <span class="string">'@tanstack/svelte-query'</span>;</span></span><br><span class="line"><span class="language-javascript"> <span class="keyword">import</span> { useIntersectionObserver } <span class="keyword">from</span> <span class="string">'runed'</span>;</span></span><br><span class="line"><span class="language-javascript"> <span class="keyword">import</span> type { <span class="title class_">Snippet</span> } <span class="keyword">from</span> <span class="string">'svelte'</span>;</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript"> <span class="comment">// [上述的类型定义]</span></span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript"> <span class="keyword">let</span> { queryOptions, children }: <span class="title class_">Props</span> = $props();</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript"> <span class="keyword">let</span> <span class="attr">el</span>: <span class="title class_">Element</span>;</span></span><br><span class="line"><span class="language-javascript"> <span class="keyword">const</span> { isIntersecting } = <span class="title function_">useIntersectionObserver</span>(</span></span><br><span class="line"><span class="language-javascript"> <span class="function">() =></span> el,</span></span><br><span class="line"><span class="language-javascript"> {</span></span><br><span class="line"><span class="language-javascript"> <span class="attr">rootMargin</span>: <span class="string">'200px'</span>,</span></span><br><span class="line"><span class="language-javascript"> }</span></span><br><span class="line"><span class="language-javascript"> );</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript"> <span class="keyword">const</span> query = <span class="title function_">createQuery</span>({</span></span><br><span class="line"><span class="language-javascript"> ...queryOptions,</span></span><br><span class="line"><span class="language-javascript"> <span class="keyword">get</span> <span class="title function_">enabled</span>() {</span></span><br><span class="line"><span class="language-javascript"> <span class="keyword">return</span> ($state.<span class="title function_">is</span>(isIntersecting) && (queryOptions.<span class="property">enabled</span> ?? <span class="literal">true</span>));</span></span><br><span class="line"><span class="language-javascript"> }</span></span><br><span class="line"><span class="language-javascript"> });</span></span><br><span class="line"><span class="language-javascript"></span><span class="tag"></<span class="name">script</span>></span></span><br><span class="line"></span><br><span class="line"><span class="tag"><<span class="name">div</span> <span class="attr">bind:this</span>=<span class="string">{el}</span>></span></span><br><span class="line"> {#snippet children({ query })}</span><br><span class="line"> {/snippet}</span><br><span class="line"><span class="tag"></<span class="name">div</span>></span></span><br></pre></td></tr></table></figure> - <ul> <li>我们创建一个 <code>div</code> 元素作为哨兵(sentinel),并用 <code>bind:this={el}</code> 将其 DOM 引用绑定到变量 <code>el</code>。</li> -<li><code>useIntersectionObserver</code> 接收一个返回目标元素的函数 <code>() => el</code>。<ul> +<li><code>useIntersectionObserver</code> 接收一个返回目标元素的函数 <code>() => el</code>。 +<ul> <li>它返回一个响应式的状态对象,其中 <code>isIntersecting</code> 是一个布尔值的符文(rune),当 <code>div</code> 元素进入 viewpoint 时为 <code>true</code>,否则为 <code>false</code>。</li> </ul> </li> -<li><code>rootMargin: '200px'</code> 是一个优化选项,它会在元素距离 viewpoint 还有 200px 时就触发加载,从而提升用户体验。</li> +<li><code>rootMargin: '200px'</code> 是一个优化选项,它会在元素距离 viewpoint 还有 200px 时就触发加载,从而提升用户体验。</li> </ul> -<h4 id="使用"><a href="#使用" class="headerlink" title="使用"></a>使用</h4><p>使用 <code>LazyQuery</code> 组件非常直观。开发者只需关注数据获取的业务逻辑,而无需关心惰性加载的实现细节,假设有一个获取图表数据的场景:</p> +<h4 id="使用"><a class="header-anchor" href="#使用">¶</a>使用</h4> +<p>使用 <code>LazyQuery</code> 组件非常直观。开发者只需关注数据获取的业务逻辑,而无需关心惰性加载的实现细节,假设有一个获取图表数据的场景:</p> <figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag"><<span class="name">script</span> <span class="attr">lang</span>=<span class="string">"ts"</span>></span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript"> <span class="keyword">import</span> { <span class="title class_">QueryClientProvider</span>, <span class="title class_">QueryClient</span> } <span class="keyword">from</span> <span class="string">'@tanstack/svelte-query'</span>;</span></span><br><span class="line"><span class="language-javascript"> <span class="keyword">import</span> <span class="title class_">LazyQuery</span> <span class="keyword">from</span> <span class="string">'./LazyQuery.svelte'</span>;</span></span><br><span class="line"><span class="language-javascript"> <span class="keyword">import</span> <span class="title class_">CopdGoldGradingChart</span> <span class="keyword">from</span> <span class="string">'./CopdGoldGradingChart.svelte'</span>;</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript"> <span class="keyword">const</span> queryClient = <span class="keyword">new</span> <span class="title class_">QueryClient</span>();</span></span><br><span class="line"><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript"> <span class="comment">// Define the query configuration object, just like with a standard `createQuery`.</span></span></span><br><span class="line"><span class="language-javascript"> <span class="keyword">const</span> queryOptions = {</span></span><br><span class="line"><span class="language-javascript"> <span class="attr">queryKey</span>: [<span class="string">'goldGradingData'</span>],</span></span><br><span class="line"><span class="language-javascript"> <span class="attr">queryFn</span>: <span class="title function_">async</span> () => {</span></span><br><span class="line"><span class="language-javascript"> <span class="comment">// Simulate a network request</span></span></span><br><span class="line"><span class="language-javascript"> <span class="keyword">await</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function"><span class="params">resolve</span> =></span> <span class="built_in">setTimeout</span>(resolve, <span class="number">1500</span>));</span></span><br><span class="line"><span class="language-javascript"> <span class="comment">// In a real application, this would be an API call</span></span></span><br><span class="line"><span class="language-javascript"> <span class="comment">// const response = await fetch('/api/gold-grading');</span></span></span><br><span class="line"><span class="language-javascript"> <span class="comment">// return await response.json();</span></span></span><br><span class="line"><span class="language-javascript"> <span class="keyword">return</span> { <span class="attr">data</span>: { <span class="attr">totalPatients</span>: <span class="number">1234</span>, <span class="attr">chartPoints</span>: [<span class="comment">/* ... */</span>] } };</span></span><br><span class="line"><span class="language-javascript"> }</span></span><br><span class="line"><span class="language-javascript"> };</span></span><br><span class="line"><span class="language-javascript"></span><span class="tag"></<span class="name">script</span>></span></span><br><span class="line"></span><br><span class="line"><span class="tag"><<span class="name">QueryClientProvider</span> <span class="attr">client</span>=<span class="string">{queryClient}</span>></span></span><br><span class="line"> <span class="tag"><<span class="name">div</span> <span class="attr">style</span>=<span class="string">"height: 200vh;"</span>></span></span><br><span class="line"> <span class="tag"><<span class="name">p</span>></span>Scroll down to see the chart...<span class="tag"></<span class="name">p</span>></span></span><br><span class="line"> <span class="tag"></<span class="name">div</span>></span></span><br><span class="line"></span><br><span class="line"> <span class="tag"><<span class="name">LazyQuery</span> {<span class="attr">queryOptions</span>}></span></span><br><span class="line"> {#snippet children({ query })}</span><br><span class="line"> {#if query.isLoading}</span><br><span class="line"> <span class="tag"><<span class="name">p</span>></span>Loading chart data...<span class="tag"></<span class="name">p</span>></span></span><br><span class="line"> {:else if query.error}</span><br><span class="line"> <span class="tag"><<span class="name">p</span>></span>Error: {query.error.message}<span class="tag"></<span class="name">p</span>></span></span><br><span class="line"> {:else if query.data}</span><br><span class="line"> <span class="tag"><<span class="name">CopdGoldGradingChart</span></span></span><br><span class="line"><span class="tag"> <span class="attr">isLoading</span>=<span class="string">{query.isFetching}</span></span></span><br><span class="line"><span class="tag"> <span class="attr">error</span>=<span class="string">{query.error}</span></span></span><br><span class="line"><span class="tag"> <span class="attr">refetch</span>=<span class="string">{()</span> =></span> query.refetch()}</span><br><span class="line"> data={query.data.data}</span><br><span class="line"> totalPatients={query.data.data.totalPatients}</span><br><span class="line"> /></span><br><span class="line"> {/if}</span><br><span class="line"> {/snippet}</span><br><span class="line"> <span class="tag"></<span class="name">LazyQuery</span>></span></span><br><span class="line"><span class="tag"></<span class="name">QueryClientProvider</span>></span></span><br></pre></td></tr></table></figure> - <ul> <li>页面初始加载时,<code>LazyQuery</code> 组件被渲染,但由于其 <code>div</code> 在 viewpoint 之外,<code>isIntersecting</code> 为 <code>false</code>。</li> <li><code>createQuery</code> 被调用,但因为 <code>enabled</code> 条件为 <code>false</code>,查询处于禁用状态,不会发起任何网络请求。</li> @@ -3018,7 +3312,8 @@ await prisma.$transaction(async tx => { <li>这个变化被 <code>createQuery</code> 的 <code>enabled</code> 访问器捕获,查询被自动激活,<code>queryFn</code> 开始执行。</li> <li>TanStack Query 负责管理后续的状态变化(<code>isFetching</code>, <code>data</code>, <code>error</code>),并驱动 <code>children</code> 片段内的 UI 自动更新。</li> </ul> -<h4 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h4><ul> +<h4 id="参考"><a class="header-anchor" href="#参考">¶</a>参考</h4> +<ul> <li><a href="https://runed.dev/docs/utilities/use-intersection-observer">https://runed.dev/docs/utilities/use-intersection-observer</a></li> <li><a href="https://tanstack.com/table/latest/docs/introduction">https://tanstack.com/table/latest/docs/introduction</a></li> </ul> @@ -3032,7 +3327,6 @@ await prisma.$transaction(async tx => { <url>/2023/08/15/tick-thread%E5%9C%A8Multicore-OCaml%E4%B8%AD%E7%9A%84%E4%BD%9C%E7%94%A8/</url> <content><![CDATA[<p>Multicore OCaml的程序在启动时会运行一个 tick thread,其实现如下:</p> <figure class="highlight c"><table><tr><td class="code"><pre><span class="line"><span class="comment">/* The tick thread: posts a SIGPREEMPTION signal periodically */</span></span><br><span class="line"></span><br><span class="line"><span class="type">static</span> <span class="type">void</span> * <span class="title function_">caml_thread_tick</span><span class="params">(<span class="type">void</span> * arg)</span></span><br><span class="line">{</span><br><span class="line"> <span class="class"><span class="keyword">struct</span> <span class="title">timeval</span> <span class="title">timeout</span>;</span></span><br><span class="line"> <span class="type">sigset_t</span> mask;</span><br><span class="line"></span><br><span class="line"> <span class="comment">/* Block all signals so that we don't try to execute an OCaml signal handler*/</span></span><br><span class="line"> sigfillset(&mask);</span><br><span class="line"> pthread_sigmask(SIG_BLOCK, &mask, <span class="literal">NULL</span>);</span><br><span class="line"> <span class="keyword">while</span>(! caml_tick_thread_stop) {</span><br><span class="line"> <span class="comment">/* select() seems to be the most efficient way to suspend the</span></span><br><span class="line"><span class="comment"> thread for sub-second intervals */</span></span><br><span class="line"> timeout.tv_sec = <span class="number">0</span>;</span><br><span class="line"> timeout.tv_usec = Thread_timeout * <span class="number">1000</span>;</span><br><span class="line"> select(<span class="number">0</span>, <span class="literal">NULL</span>, <span class="literal">NULL</span>, <span class="literal">NULL</span>, &timeout);</span><br><span class="line"> <span class="comment">/* The preemption signal should never cause a callback, so don't</span></span><br><span class="line"><span class="comment"> go through caml_handle_signal(), just record signal delivery via</span></span><br><span class="line"><span class="comment"> caml_record_signal(). */</span></span><br><span class="line"> caml_record_signal(SIGPREEMPTION);</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">return</span> <span class="literal">NULL</span>;</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - <p>这是因为Multicore OCaml的GC目前需要一个进程(或一个Domain)中的所有线程一起参与以避免并发访问。如果一个线程在system call上被阻塞,那么整个Domain就会被卡住,直到该线程可以参与当前的垃圾收集。为了避免这个问题,tick 线程可以代替被阻塞的线程执行垃圾收集操作。</p> ]]></content> <tags> @@ -3043,23 +3337,31 @@ await prisma.$transaction(async tx => { <title>UUID v7 是如何加快 RDBMS 索引速度的</title> <url>/2025/04/13/uuidv7-rdbms/</url> <content><![CDATA[<p>UUID v7 之所以能显著提升关系型数据库(尤其是采用聚集索引的 MySQL InnoDB)在插入和查询速度,主要归功于它在 ID 中引入了“可排序的时间戳前缀”,从而大幅减少了 B-Tree 索引页分裂(page split)和数据碎片化。这里分几点来说:</p> -<p>一、 聚集索引(Clustered Index)的插入机制 </p> +<p>一、 聚集索引(Clustered Index)的插入机制</p> <p>在 InnoDB 中,聚集索引的叶子节点同时存储了行数据,且按照索引键(主键)顺序物理排序。</p> -<p>当新记录的主键完全随机(如 UUID v4)时,每次插入都会随机落在 B-Tree 的不同叶子页,导致频繁的页分裂和指针重排,而页分裂和随机 I/O 会带来大量的磁盘写放大和缓存抖动(cache churn),削弱吞吐并拉高延迟。</p> -<p>二、UUID v7 的时间排序特性 </p> -<p>UUID v7 在高位(前 48 位)嵌入了以毫秒级精度的 Unix 时间戳,剩下的位用于随机数或序列号,这样生成的 ID 保持全局唯一性的同时,随着时间自然递增(即“近似单调递增”),新插入的记录几乎总是追加到 B-Tree 的最右端叶子节点。 </p> -<p>参见 dbaplus.cn 的分析: </p> +<p>当新记录的主键完全随机(如 UUID v4)时,每次插入都会随机落在 B-Tree 的不同叶子页,导致频繁的页分裂和指针重排,而页分裂和随机 I/O 会带来大量的磁盘写放大和缓存抖动(cache churn),削弱吞吐并拉高延迟。</p> +<p>二、UUID v7 的时间排序特性</p> +<p>UUID v7 在高位(前 48 位)嵌入了以毫秒级精度的 Unix 时间戳,剩下的位用于随机数或序列号,这样生成的 ID 保持全局唯一性的同时,随着时间自然递增(即“近似单调递增”),新插入的记录几乎总是追加到 B-Tree 的最右端叶子节点。</p> +<p>参见 <a href="http://dbaplus.cn">dbaplus.cn</a> 的分析:</p> <blockquote> <p>“UUID v7 的创新之处在于其时间排序特性,它在前 48 位中嵌入了以毫秒为单位的 Unix 时间戳……可能在插入和查询操作上提供更好的性能”【1】。</p> </blockquote> -<p>三、降低页分裂与碎片化 </p> +<p>三、降低页分裂与碎片化</p> <p>顺序或近似顺序的主键能使叶子节点连续增长,极少触发页分裂,并且更少的页分裂意味着更低的写放大(write amplification)和更稳定的插入延迟,同时,减少了空洞和链表重排,提高了磁盘和内存缓存的命中率。</p> -<p>四、提升查询局部性与缓存命中 </p> -<p>因为数据物理上是按时间顺序紧凑写入,时间范围查询(如 “最近 1 小时的日志”)可以快速定位连续的叶子页,I/O 更聚集,内存缓冲池(buffer pool)或操作系统页缓存能更有效地缓存最近热数据,进一步加速查询。</p> +<p>四、提升查询局部性与缓存命中</p> +<p>因为数据物理上是按时间顺序紧凑写入,时间范围查询(如 “最近 1 小时的日志”)可以快速定位连续的叶子页,I/O 更聚集,内存缓冲池(buffer pool)或操作系统页缓存能更有效地缓存最近热数据,进一步加速查询。</p> <hr> -<p>Rimon Tawadrous 在其 GitHub repo 中的测试,对比 100 万条逐条插入实验,UUID v7 相较 UUID v4 在单线程插入上速度快约 3.24%,多线程下更可观【1】。 </p> +<p>Rimon Tawadrous 在其 GitHub repo 中的测试,对比 100 万条逐条插入实验,UUID v7 相较 UUID v4 在单线程插入上速度快约 3.24%,多线程下更可观【1】。</p> <hr> -<p>参考链接<br>[1] “为什么 UUID 7 比 UUID 4 更适合作为 RDBMS 的聚集索引?” dbaplus.cn<br> <a href="https://dbaplus.cn/news-160-6313-1.html">https://dbaplus.cn/news-160-6313-1.html</a><br>[2] “PostgreSQL and UUID as primary key” maciejwalkowiak<br> <a href="https://maciejwalkowiak.com/blog/postgres-uuid-primary-key/">https://maciejwalkowiak.com/blog/postgres-uuid-primary-key/</a><br>[3] “Optimised UUIDs in mysql” stitcher<br> <a href="https://stitcher.io/blog/optimised-uuids-in-mysql">https://stitcher.io/blog/optimised-uuids-in-mysql</a><br>[3] “Storing UUID Values in MySQL” percona<br> <a href="https://www.percona.com/blog/store-uuid-optimized-way/">https://www.percona.com/blog/store-uuid-optimized-way/</a></p> +<p>参考链接<br> +[1] “为什么 UUID 7 比 UUID 4 更适合作为 RDBMS 的聚集索引?” <a href="http://dbaplus.cn">dbaplus.cn</a><br> +<a href="https://dbaplus.cn/news-160-6313-1.html">https://dbaplus.cn/news-160-6313-1.html</a><br> +[2] “PostgreSQL and UUID as primary key” maciejwalkowiak<br> +<a href="https://maciejwalkowiak.com/blog/postgres-uuid-primary-key/">https://maciejwalkowiak.com/blog/postgres-uuid-primary-key/</a><br> +[3] “Optimised UUIDs in mysql” stitcher<br> +<a href="https://stitcher.io/blog/optimised-uuids-in-mysql">https://stitcher.io/blog/optimised-uuids-in-mysql</a><br> +[3] “Storing UUID Values in MySQL” percona<br> +<a href="https://www.percona.com/blog/store-uuid-optimized-way/">https://www.percona.com/blog/store-uuid-optimized-way/</a></p> ]]></content> <tags> <tag>Technique</tag> @@ -3074,25 +3376,20 @@ await prisma.$transaction(async tx => { </ul> <p>在很多地方都能看到:</p> <figure class="highlight c++"><table><tr><td class="code"><pre><span class="line">*isolate-><span class="built_in">factory</span>()-><span class="built_in">NumberToString</span>(value);</span><br></pre></td></tr></table></figure> -<p>例如 <a href="https://github.com/v8/v8/blob/df99ca37a9d02a3318d3e5487c7803f6230b8f5f/src/builtins/builtins-number.cc#L140">/src/builtins/builtins-number.cc</a> 中。</p> -<p>下面看看<code>NumberToString</code>的定义, 应该是在 <a href="https://github.com/v8/v8/blob/829e8d18d73e21807c78223b0cc107c76c80da27/src/heap/factory-base.cc#L963-L978">src/heap/factory-base.cc</a> 中:</p> +<p>例如 <a href="https://github.com/v8/v8/blob/df99ca37a9d02a3318d3e5487c7803f6230b8f5f/src/builtins/builtins-number.cc#L140">/src/builtins/builtins-number.cc</a> 中。</p> +<p>下面看看<code>NumberToString</code>的定义, 应该是在 <a href="https://github.com/v8/v8/blob/829e8d18d73e21807c78223b0cc107c76c80da27/src/heap/factory-base.cc#L963-L978">src/heap/factory-base.cc</a> 中:</p> <figure class="highlight c++"><table><tr><td class="code"><pre><span class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> Impl></span><br><span class="line">Handle<String> FactoryBase<Impl>::<span class="built_in">NumberToString</span>(Handle<Object> number,</span><br><span class="line"> NumberCacheMode mode) {</span><br><span class="line"> <span class="built_in">SLOW_DCHECK</span>(<span class="built_in">IsNumber</span>(*number));</span><br><span class="line"> <span class="keyword">if</span> (<span class="built_in">IsSmi</span>(*number)) <span class="keyword">return</span> <span class="built_in">SmiToString</span>(Smi::<span class="built_in">cast</span>(*number), mode);</span><br><span class="line"></span><br><span class="line"> <span class="type">double</span> double_value = Handle<HeapNumber>::<span class="built_in">cast</span>(number)-><span class="built_in">value</span>();</span><br><span class="line"> <span class="comment">// Try to canonicalize doubles.</span></span><br><span class="line"> <span class="type">int</span> smi_value;</span><br><span class="line"> <span class="keyword">if</span> (<span class="built_in">DoubleToSmiInteger</span>(double_value, &smi_value)) {</span><br><span class="line"> <span class="keyword">return</span> <span class="built_in">SmiToString</span>(Smi::<span class="built_in">FromInt</span>(smi_value), mode);</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">return</span> <span class="built_in">HeapNumberToString</span>(Handle<HeapNumber>::<span class="built_in">cast</span>(number), double_value,</span><br><span class="line"> mode);</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - <p>可以看到这里调用了 <code>SmiToString</code>, 这里不往下翻这个函数的定义, 只需要知道Smi是什么即可。 Smi 是一种特殊的整数类型,它被用于表示较小的整数值,通常在 32 位系统中是 31 位有符号整数。Smi 类型的值存储在指针的低位,而指针的高位用于标记该值是一个 Smi 类型。<code>IsSmi</code> 函数会检查给定的值是否为 Smi 类型,如果是,则返回 true,否则返回 false。这个函数通常用于 V8 引擎内部的优化和性能优化。</p> <p>所以<code>NumberToString</code>会判断number是否是一个smi, 如果是的话就调用SmiToString, 否则会尝试将其转换为double再去调用<code>DoubleToSmiInteger</code>, 将<code>DoubleToSmiInteger</code>的调用结果存在<code>smi_value</code>里面, 再通过调用<code>SmiToString</code>将<code>smi_value</code>转换为字符串。</p> <p>如果这两条路都行不通的话,就直接调用<code>HeapNumberToString</code>了。</p> <p><code>HeapNumberToString</code>的定义如下:</p> <figure class="highlight c++"><table><tr><td class="code"><pre><span class="line"><span class="keyword">template</span> <<span class="keyword">typename</span> Impl></span><br><span class="line">Handle<String> FactoryBase<Impl>::<span class="built_in">HeapNumberToString</span>(Handle<HeapNumber> number,</span><br><span class="line"> <span class="type">double</span> value,</span><br><span class="line"> NumberCacheMode mode) {</span><br><span class="line"> <span class="type">int</span> hash = mode == NumberCacheMode::kIgnore</span><br><span class="line"> ? <span class="number">0</span></span><br><span class="line"> : <span class="built_in">impl</span>()-><span class="built_in">NumberToStringCacheHash</span>(value);</span><br><span class="line"></span><br><span class="line"> <span class="keyword">if</span> (mode == NumberCacheMode::kBoth) {</span><br><span class="line"> Handle<Object> cached = <span class="built_in">impl</span>()-><span class="built_in">NumberToStringCacheGet</span>(*number, hash);</span><br><span class="line"> <span class="keyword">if</span> (!<span class="built_in">IsUndefined</span>(*cached, <span class="built_in">isolate</span>())) <span class="keyword">return</span> Handle<String>::<span class="built_in">cast</span>(cached);</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> Handle<String> result;</span><br><span class="line"> <span class="keyword">if</span> (value == <span class="number">0</span>) {</span><br><span class="line"> result = <span class="built_in">zero_string</span>();</span><br><span class="line"> } <span class="keyword">else</span> <span class="keyword">if</span> (std::<span class="built_in">isnan</span>(value)) {</span><br><span class="line"> result = <span class="built_in">NaN_string</span>();</span><br><span class="line"> } <span class="keyword">else</span> {</span><br><span class="line"> <span class="type">char</span> arr[kNumberToStringBufferSize];</span><br><span class="line"> <span class="function">base::Vector<<span class="type">char</span>> <span class="title">buffer</span><span class="params">(arr, arraysize(arr))</span></span>;</span><br><span class="line"> <span class="type">const</span> <span class="type">char</span>* string = <span class="built_in">DoubleToCString</span>(value, buffer);</span><br><span class="line"> result = <span class="built_in">CharToString</span>(<span class="keyword">this</span>, string, mode);</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">if</span> (mode != NumberCacheMode::kIgnore) {</span><br><span class="line"> <span class="built_in">impl</span>()-><span class="built_in">NumberToStringCacheSet</span>(number, hash, result);</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">return</span> result;</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - <p>就是熟知的NaN, Undefined处理,重点在:</p> <figure class="highlight c++"><table><tr><td class="code"><pre><span class="line"><span class="type">char</span> arr[kNumberToStringBufferSize];</span><br><span class="line"><span class="function">base::Vector<<span class="type">char</span>> <span class="title">buffer</span><span class="params">(arr, arraysize(arr))</span></span>;</span><br><span class="line"><span class="type">const</span> <span class="type">char</span>* string = <span class="built_in">DoubleToCString</span>(value, buffer);</span><br><span class="line">result = <span class="built_in">CharToString</span>(<span class="keyword">this</span>, string, mode);</span><br></pre></td></tr></table></figure> - -<p>这里调用了<code>DoubleToCString</code>, 其定义在 <a href="https://github.com/v8/v8/blob/829e8d18d73e21807c78223b0cc107c76c80da27/src/numbers/conversions.cc#L1064-L1126">/src/numbers/conversions.cc</a> 中:</p> +<p>这里调用了<code>DoubleToCString</code>, 其定义在 <a href="https://github.com/v8/v8/blob/829e8d18d73e21807c78223b0cc107c76c80da27/src/numbers/conversions.cc#L1064-L1126">/src/numbers/conversions.cc</a> 中:</p> <figure class="highlight c++"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="type">const</span> <span class="type">char</span>* <span class="title">DoubleToCString</span><span class="params">(<span class="type">double</span> v, base::Vector<<span class="type">char</span>> buffer)</span> </span>{</span><br><span class="line"> <span class="keyword">switch</span> (FPCLASSIFY_NAMESPACE::<span class="built_in">fpclassify</span>(v)) {</span><br><span class="line"> <span class="keyword">case</span> FP_NAN:</span><br><span class="line"> <span class="keyword">return</span> <span class="string">"NaN"</span>;</span><br><span class="line"> <span class="keyword">case</span> FP_INFINITE:</span><br><span class="line"> <span class="keyword">return</span> (v < <span class="number">0.0</span> ? <span class="string">"-Infinity"</span> : <span class="string">"Infinity"</span>);</span><br><span class="line"> <span class="keyword">case</span> FP_ZERO:</span><br><span class="line"> <span class="keyword">return</span> <span class="string">"0"</span>;</span><br><span class="line"> <span class="keyword">default</span>: {</span><br><span class="line"> <span class="keyword">if</span> (<span class="built_in">IsInt32Double</span>(v)) {</span><br><span class="line"> <span class="comment">// This will trigger if v is -0 and -0.0 is stringified to "0".</span></span><br><span class="line"> <span class="comment">// (see ES section 7.1.12.1 #sec-tostring-applied-to-the-number-type)</span></span><br><span class="line"> <span class="keyword">return</span> <span class="built_in">IntToCString</span>(<span class="built_in">FastD2I</span>(v), buffer);</span><br><span class="line"> }</span><br><span class="line"> <span class="function">SimpleStringBuilder <span class="title">builder</span><span class="params">(buffer.begin(), buffer.length())</span></span>;</span><br><span class="line"> <span class="type">int</span> decimal_point;</span><br><span class="line"> <span class="type">int</span> sign;</span><br><span class="line"> <span class="type">const</span> <span class="type">int</span> kV8DtoaBufferCapacity = base::kBase10MaximalLength + <span class="number">1</span>;</span><br><span class="line"> <span class="type">char</span> decimal_rep[kV8DtoaBufferCapacity];</span><br><span class="line"> <span class="type">int</span> length;</span><br><span class="line"></span><br><span class="line"> base::<span class="built_in">DoubleToAscii</span>(</span><br><span class="line"> v, base::DTOA_SHORTEST, <span class="number">0</span>,</span><br><span class="line"> base::<span class="built_in">Vector</span><<span class="type">char</span>>(decimal_rep, kV8DtoaBufferCapacity), &sign,</span><br><span class="line"> &length, &decimal_point);</span><br><span class="line"></span><br><span class="line"> <span class="keyword">if</span> (sign) builder.<span class="built_in">AddCharacter</span>(<span class="string">'-'</span>);</span><br><span class="line"></span><br><span class="line"> <span class="keyword">if</span> (length <= decimal_point && decimal_point <= <span class="number">21</span>) {</span><br><span class="line"> <span class="comment">// ECMA-262 section 9.8.1 step 6.</span></span><br><span class="line"> builder.<span class="built_in">AddString</span>(decimal_rep);</span><br><span class="line"> builder.<span class="built_in">AddPadding</span>(<span class="string">'0'</span>, decimal_point - length);</span><br><span class="line"></span><br><span class="line"> } <span class="keyword">else</span> <span class="keyword">if</span> (<span class="number">0</span> < decimal_point && decimal_point <= <span class="number">21</span>) {</span><br><span class="line"> <span class="comment">// ECMA-262 section 9.8.1 step 7.</span></span><br><span class="line"> builder.<span class="built_in">AddSubstring</span>(decimal_rep, decimal_point);</span><br><span class="line"> builder.<span class="built_in">AddCharacter</span>(<span class="string">'.'</span>);</span><br><span class="line"> builder.<span class="built_in">AddString</span>(decimal_rep + decimal_point);</span><br><span class="line"></span><br><span class="line"> } <span class="keyword">else</span> <span class="keyword">if</span> (decimal_point <= <span class="number">0</span> && decimal_point > <span class="number">-6</span>) {</span><br><span class="line"> <span class="comment">// ECMA-262 section 9.8.1 step 8.</span></span><br><span class="line"> builder.<span class="built_in">AddString</span>(<span class="string">"0."</span>);</span><br><span class="line"> builder.<span class="built_in">AddPadding</span>(<span class="string">'0'</span>, -decimal_point);</span><br><span class="line"> builder.<span class="built_in">AddString</span>(decimal_rep);</span><br><span class="line"></span><br><span class="line"> } <span class="keyword">else</span> {</span><br><span class="line"> <span class="comment">// ECMA-262 section 9.8.1 step 9 and 10 combined.</span></span><br><span class="line"> builder.<span class="built_in">AddCharacter</span>(decimal_rep[<span class="number">0</span>]);</span><br><span class="line"> <span class="keyword">if</span> (length != <span class="number">1</span>) {</span><br><span class="line"> builder.<span class="built_in">AddCharacter</span>(<span class="string">'.'</span>);</span><br><span class="line"> builder.<span class="built_in">AddString</span>(decimal_rep + <span class="number">1</span>);</span><br><span class="line"> }</span><br><span class="line"> builder.<span class="built_in">AddCharacter</span>(<span class="string">'e'</span>);</span><br><span class="line"> builder.<span class="built_in">AddCharacter</span>((decimal_point >= <span class="number">0</span>) ? <span class="string">'+'</span> : <span class="string">'-'</span>);</span><br><span class="line"> <span class="type">int</span> exponent = decimal_point - <span class="number">1</span>;</span><br><span class="line"> <span class="keyword">if</span> (exponent < <span class="number">0</span>) exponent = -exponent;</span><br><span class="line"> builder.<span class="built_in">AddDecimalInteger</span>(exponent);</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">return</span> builder.<span class="built_in">Finalize</span>();</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - <p>不用过多解释, 已经很清晰了, <code>FastD2I</code> 就是 Fast Double to Integer的意思, 定义如下, 注释也很详尽:</p> <figure class="highlight c++"><table><tr><td class="code"><pre><span class="line"><span class="comment">// The fast double-to-(unsigned-)int conversion routine does not guarantee</span></span><br><span class="line"><span class="comment">// rounding towards zero.</span></span><br><span class="line"><span class="comment">// The result is undefined if x is infinite or NaN, or if the rounded</span></span><br><span class="line"><span class="comment">// integer value is outside the range of type int.</span></span><br><span class="line"><span class="function"><span class="keyword">inline</span> <span class="type">int</span> <span class="title">FastD2I</span><span class="params">(<span class="type">double</span> x)</span> </span>{</span><br><span class="line"> <span class="built_in">DCHECK</span>(x <= INT_MAX);</span><br><span class="line"> <span class="built_in">DCHECK</span>(x >= INT_MIN);</span><br><span class="line"> <span class="keyword">return</span> <span class="built_in">static_cast</span><<span class="type">int32_t</span>>(x);</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - <p>以上</p> ]]></content> <tags> @@ -3120,7 +3417,7 @@ await prisma.$transaction(async tx => { <p>对于登录功能,需要考虑:</p> <ul> <li>UI 层:登录表单(输入邮箱、密码的地方)、提交按钮、错误提示信息。</li> -<li>API/服务层:接收登录请求、验证用户凭证的接口。</li> +<li>API/服务层:接收登录请求、验证用户凭证的接口。</li> <li>业务逻辑层:校验输入格式、查询用户信息、验证密码、生成会话(Session)或令牌(Token)。</li> <li>数据访问层:从数据库中读取用户信息。</li> </ul> @@ -3289,8 +3586,10 @@ await prisma.$transaction(async tx => { <p>它们是因缘聚散吗?</p> <p>那露珠消散后去了哪里?</p> <p>此有故彼有,此生故彼灭。</p> -<p>当晨光加热露珠表面至 <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.489ex;" xmlns="http://www.w3.org/2000/svg" width="6.242ex" height="1.995ex" role="img" focusable="false" viewBox="0 -666 2759 882"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="mn"><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z"></path><path data-c="2E" d="M78 60Q78 84 95 102T138 120Q162 120 180 104T199 61Q199 36 182 18T139 0T96 17T78 60Z" transform="translate(500,0)"></path><path data-c="31" d="M213 578L200 573Q186 568 160 563T102 556H83V602H102Q149 604 189 617T245 641T273 663Q275 666 285 666Q294 666 302 660V361L303 61Q310 54 315 52T339 48T401 46H427V0H416Q395 3 257 3Q121 3 100 0H88V46H114Q136 46 152 46T177 47T193 50T201 52T207 57T213 61V578Z" transform="translate(778,0)"></path></g><g data-mml-node="mi" transform="translate(1278,0)"><path data-c="1D707" d="M58 -216Q44 -216 34 -208T23 -186Q23 -176 96 116T173 414Q186 442 219 442Q231 441 239 435T249 423T251 413Q251 401 220 279T187 142Q185 131 185 107V99Q185 26 252 26Q261 26 270 27T287 31T302 38T315 45T327 55T338 65T348 77T356 88T365 100L372 110L408 253Q444 395 448 404Q461 431 491 431Q504 431 512 424T523 412T525 402L449 84Q448 79 448 68Q448 43 455 35T476 26Q485 27 496 35Q517 55 537 131Q543 151 547 152Q549 153 557 153H561Q580 153 580 144Q580 138 575 117T555 63T523 13Q510 0 491 -8Q483 -10 467 -10Q446 -10 429 -4T402 11T385 29T376 44T374 51L368 45Q362 39 350 30T324 12T288 -4T246 -11Q199 -11 153 12L129 -85Q108 -167 104 -180T92 -202Q76 -216 58 -216Z"></path></g><g data-mml-node="mi" transform="translate(1881,0)"><path data-c="1D45A" d="M21 287Q22 293 24 303T36 341T56 388T88 425T132 442T175 435T205 417T221 395T229 376L231 369Q231 367 232 367L243 378Q303 442 384 442Q401 442 415 440T441 433T460 423T475 411T485 398T493 385T497 373T500 364T502 357L510 367Q573 442 659 442Q713 442 746 415T780 336Q780 285 742 178T704 50Q705 36 709 31T724 26Q752 26 776 56T815 138Q818 149 821 151T837 153Q857 153 857 145Q857 144 853 130Q845 101 831 73T785 17T716 -10Q669 -10 648 17T627 73Q627 92 663 193T700 345Q700 404 656 404H651Q565 404 506 303L499 291L466 157Q433 26 428 16Q415 -11 385 -11Q372 -11 364 -4T353 8T350 18Q350 29 384 161L420 307Q423 322 423 345Q423 404 379 404H374Q288 404 229 303L222 291L189 157Q156 26 151 16Q138 -11 108 -11Q95 -11 87 -5T76 7T74 17Q74 30 112 181Q151 335 151 342Q154 357 154 369Q154 405 129 405Q107 405 92 377T69 316T57 280Q55 278 41 278H27Q21 284 21 287Z"></path></g></g></g></svg></mjx-container> 深度时,表层水分子动能突破氢键束缚(键能约 <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.566ex;" xmlns="http://www.w3.org/2000/svg" width="9.762ex" height="2.262ex" role="img" focusable="false" viewBox="0 -750 4315 1000"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="mn"><path data-c="32" d="M109 429Q82 429 66 447T50 491Q50 562 103 614T235 666Q326 666 387 610T449 465Q449 422 429 383T381 315T301 241Q265 210 201 149L142 93L218 92Q375 92 385 97Q392 99 409 186V189H449V186Q448 183 436 95T421 3V0H50V19V31Q50 38 56 46T86 81Q115 113 136 137Q145 147 170 174T204 211T233 244T261 278T284 308T305 340T320 369T333 401T340 431T343 464Q343 527 309 573T212 619Q179 619 154 602T119 569T109 550Q109 549 114 549Q132 549 151 535T170 489Q170 464 154 447T109 429Z"></path><path data-c="33" d="M127 463Q100 463 85 480T69 524Q69 579 117 622T233 665Q268 665 277 664Q351 652 390 611T430 522Q430 470 396 421T302 350L299 348Q299 347 308 345T337 336T375 315Q457 262 457 175Q457 96 395 37T238 -22Q158 -22 100 21T42 130Q42 158 60 175T105 193Q133 193 151 175T169 130Q169 119 166 110T159 94T148 82T136 74T126 70T118 67L114 66Q165 21 238 21Q293 21 321 74Q338 107 338 175V195Q338 290 274 322Q259 328 213 329L171 330L168 332Q166 335 166 348Q166 366 174 366Q202 366 232 371Q266 376 294 413T322 525V533Q322 590 287 612Q265 626 240 626Q208 626 181 615T143 592T132 580H135Q138 579 143 578T153 573T165 566T175 555T183 540T186 520Q186 498 172 481T127 463Z" transform="translate(500,0)"></path></g><g data-mml-node="mi" transform="translate(1000,0)"><path data-c="1D458" d="M121 647Q121 657 125 670T137 683Q138 683 209 688T282 694Q294 694 294 686Q294 679 244 477Q194 279 194 272Q213 282 223 291Q247 309 292 354T362 415Q402 442 438 442Q468 442 485 423T503 369Q503 344 496 327T477 302T456 291T438 288Q418 288 406 299T394 328Q394 353 410 369T442 390L458 393Q446 405 434 405H430Q398 402 367 380T294 316T228 255Q230 254 243 252T267 246T293 238T320 224T342 206T359 180T365 147Q365 130 360 106T354 66Q354 26 381 26Q429 26 459 145Q461 153 479 153H483Q499 153 499 144Q499 139 496 130Q455 -11 378 -11Q333 -11 305 15T277 90Q277 108 280 121T283 145Q283 167 269 183T234 206T200 217T182 220H180Q168 178 159 139T145 81T136 44T129 20T122 7T111 -2Q98 -11 83 -11Q66 -11 57 -1T48 16Q48 26 85 176T158 471L195 616Q196 629 188 632T149 637H144Q134 637 131 637T124 640T121 647Z"></path></g><g data-mml-node="mi" transform="translate(1521,0)"><path data-c="1D43D" d="M447 625Q447 637 354 637H329Q323 642 323 645T325 664Q329 677 335 683H352Q393 681 498 681Q541 681 568 681T605 682T619 682Q633 682 633 672Q633 670 630 658Q626 642 623 640T604 637Q552 637 545 623Q541 610 483 376Q420 128 419 127Q397 64 333 21T195 -22Q137 -22 97 8T57 88Q57 130 80 152T132 174Q177 174 182 130Q182 98 164 80T123 56Q115 54 115 53T122 44Q148 15 197 15Q235 15 271 47T324 130Q328 142 387 380T447 625Z"></path></g><g data-mml-node="TeXAtom" data-mjx-texclass="ORD" transform="translate(2154,0)"><g data-mml-node="mo"><path data-c="2F" d="M423 750Q432 750 438 744T444 730Q444 725 271 248T92 -240Q85 -250 75 -250Q68 -250 62 -245T56 -231Q56 -221 230 257T407 740Q411 750 423 750Z"></path></g></g><g data-mml-node="mi" transform="translate(2654,0)"><path data-c="1D45A" d="M21 287Q22 293 24 303T36 341T56 388T88 425T132 442T175 435T205 417T221 395T229 376L231 369Q231 367 232 367L243 378Q303 442 384 442Q401 442 415 440T441 433T460 423T475 411T485 398T493 385T497 373T500 364T502 357L510 367Q573 442 659 442Q713 442 746 415T780 336Q780 285 742 178T704 50Q705 36 709 31T724 26Q752 26 776 56T815 138Q818 149 821 151T837 153Q857 153 857 145Q857 144 853 130Q845 101 831 73T785 17T716 -10Q669 -10 648 17T627 73Q627 92 663 193T700 345Q700 404 656 404H651Q565 404 506 303L499 291L466 157Q433 26 428 16Q415 -11 385 -11Q372 -11 364 -4T353 8T350 18Q350 29 384 161L420 307Q423 322 423 345Q423 404 379 404H374Q288 404 229 303L222 291L189 157Q156 26 151 16Q138 -11 108 -11Q95 -11 87 -5T76 7T74 17Q74 30 112 181Q151 335 151 342Q154 357 154 369Q154 405 129 405Q107 405 92 377T69 316T57 280Q55 278 41 278H27Q21 284 21 287Z"></path></g><g data-mml-node="mi" transform="translate(3532,0)"><path data-c="1D45C" d="M201 -11Q126 -11 80 38T34 156Q34 221 64 279T146 380Q222 441 301 441Q333 441 341 440Q354 437 367 433T402 417T438 387T464 338T476 268Q476 161 390 75T201 -11ZM121 120Q121 70 147 48T206 26Q250 26 289 58T351 142Q360 163 374 216T388 308Q388 352 370 375Q346 405 306 405Q243 405 195 347Q158 303 140 230T121 120Z"></path></g><g data-mml-node="mi" transform="translate(4017,0)"><path data-c="1D459" d="M117 59Q117 26 142 26Q179 26 205 131Q211 151 215 152Q217 153 225 153H229Q238 153 241 153T246 151T248 144Q247 138 245 128T234 90T214 43T183 6T137 -11Q101 -11 70 11T38 85Q38 97 39 102L104 360Q167 615 167 623Q167 626 166 628T162 632T157 634T149 635T141 636T132 637T122 637Q112 637 109 637T101 638T95 641T94 647Q94 649 96 661Q101 680 107 682T179 688Q194 689 213 690T243 693T254 694Q266 694 266 686Q266 675 193 386T118 83Q118 81 118 75T117 65V59Z"></path></g></g></g></svg></mjx-container>)。<br>这种相变并非整齐划一的队列解散,而是呈现量子隧穿效应——单个水分子以 <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.05ex;" xmlns="http://www.w3.org/2000/svg" width="6.356ex" height="2.005ex" role="img" focusable="false" viewBox="0 -864 2809.2 886"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="msup"><g data-mml-node="mn"><path data-c="31" d="M213 578L200 573Q186 568 160 563T102 556H83V602H102Q149 604 189 617T245 641T273 663Q275 666 285 666Q294 666 302 660V361L303 61Q310 54 315 52T339 48T401 46H427V0H416Q395 3 257 3Q121 3 100 0H88V46H114Q136 46 152 46T177 47T193 50T201 52T207 57T213 61V578Z"></path><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z" transform="translate(500,0)"></path></g><g data-mml-node="TeXAtom" transform="translate(1033,393.1) scale(0.707)" data-mjx-texclass="ORD"><g data-mml-node="mo"><path data-c="2212" d="M84 237T84 250T98 270H679Q694 262 694 250T679 230H98Q84 237 84 250Z"></path></g><g data-mml-node="mn" transform="translate(778,0)"><path data-c="31" d="M213 578L200 573Q186 568 160 563T102 556H83V602H102Q149 604 189 617T245 641T273 663Q275 666 285 666Q294 666 302 660V361L303 61Q310 54 315 52T339 48T401 46H427V0H416Q395 3 257 3Q121 3 100 0H88V46H114Q136 46 152 46T177 47T193 50T201 52T207 57T213 61V578Z"></path><path data-c="32" d="M109 429Q82 429 66 447T50 491Q50 562 103 614T235 666Q326 666 387 610T449 465Q449 422 429 383T381 315T301 241Q265 210 201 149L142 93L218 92Q375 92 385 97Q392 99 409 186V189H449V186Q448 183 436 95T421 3V0H50V19V31Q50 38 56 46T86 81Q115 113 136 137Q145 147 170 174T204 211T233 244T261 278T284 308T305 340T320 369T333 401T340 431T343 464Q343 527 309 573T212 619Q179 619 154 602T119 569T109 550Q109 549 114 549Q132 549 151 535T170 489Q170 464 154 447T109 429Z" transform="translate(500,0)"></path></g></g></g><g data-mml-node="mi" transform="translate(2340.2,0)"><path data-c="1D460" d="M131 289Q131 321 147 354T203 415T300 442Q362 442 390 415T419 355Q419 323 402 308T364 292Q351 292 340 300T328 326Q328 342 337 354T354 372T367 378Q368 378 368 379Q368 382 361 388T336 399T297 405Q249 405 227 379T204 326Q204 301 223 291T278 274T330 259Q396 230 396 163Q396 135 385 107T352 51T289 7T195 -10Q118 -10 86 19T53 87Q53 126 74 143T118 160Q133 160 146 151T160 120Q160 94 142 76T111 58Q109 57 108 57T107 55Q108 52 115 47T146 34T201 27Q237 27 263 38T301 66T318 97T323 122Q323 150 302 164T254 181T195 196T148 231Q131 256 131 289Z"></path></g></g></g></svg></mjx-container> 量级的涨落,在液态与气态间振荡,直到完全脱离范德华力作用半径(约 <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.05ex;" xmlns="http://www.w3.org/2000/svg" width="6.235ex" height="1.557ex" role="img" focusable="false" viewBox="0 -666 2756 688"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="mn"><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z"></path><path data-c="2E" d="M78 60Q78 84 95 102T138 120Q162 120 180 104T199 61Q199 36 182 18T139 0T96 17T78 60Z" transform="translate(500,0)"></path><path data-c="33" d="M127 463Q100 463 85 480T69 524Q69 579 117 622T233 665Q268 665 277 664Q351 652 390 611T430 522Q430 470 396 421T302 350L299 348Q299 347 308 345T337 336T375 315Q457 262 457 175Q457 96 395 37T238 -22Q158 -22 100 21T42 130Q42 158 60 175T105 193Q133 193 151 175T169 130Q169 119 166 110T159 94T148 82T136 74T126 70T118 67L114 66Q165 21 238 21Q293 21 321 74Q338 107 338 175V195Q338 290 274 322Q259 328 213 329L171 330L168 332Q166 335 166 348Q166 366 174 366Q202 366 232 371Q266 376 294 413T322 525V533Q322 590 287 612Q265 626 240 626Q208 626 181 615T143 592T132 580H135Q138 579 143 578T153 573T165 566T175 555T183 540T186 520Q186 498 172 481T127 463Z" transform="translate(778,0)"></path></g><g data-mml-node="mi" transform="translate(1278,0)"><path data-c="1D45B" d="M21 287Q22 293 24 303T36 341T56 388T89 425T135 442Q171 442 195 424T225 390T231 369Q231 367 232 367L243 378Q304 442 382 442Q436 442 469 415T503 336T465 179T427 52Q427 26 444 26Q450 26 453 27Q482 32 505 65T540 145Q542 153 560 153Q580 153 580 145Q580 144 576 130Q568 101 554 73T508 17T439 -10Q392 -10 371 17T350 73Q350 92 386 193T423 345Q423 404 379 404H374Q288 404 229 303L222 291L189 157Q156 26 151 16Q138 -11 108 -11Q95 -11 87 -5T76 7T74 17Q74 30 112 180T152 343Q153 348 153 366Q153 405 129 405Q91 405 66 305Q60 285 60 284Q58 278 41 278H27Q21 284 21 287Z"></path></g><g data-mml-node="mi" transform="translate(1878,0)"><path data-c="1D45A" d="M21 287Q22 293 24 303T36 341T56 388T88 425T132 442T175 435T205 417T221 395T229 376L231 369Q231 367 232 367L243 378Q303 442 384 442Q401 442 415 440T441 433T460 423T475 411T485 398T493 385T497 373T500 364T502 357L510 367Q573 442 659 442Q713 442 746 415T780 336Q780 285 742 178T704 50Q705 36 709 31T724 26Q752 26 776 56T815 138Q818 149 821 151T837 153Q857 153 857 145Q857 144 853 130Q845 101 831 73T785 17T716 -10Q669 -10 648 17T627 73Q627 92 663 193T700 345Q700 404 656 404H651Q565 404 506 303L499 291L466 157Q433 26 428 16Q415 -11 385 -11Q372 -11 364 -4T353 8T350 18Q350 29 384 161L420 307Q423 322 423 345Q423 404 379 404H374Q288 404 229 303L222 291L189 157Q156 26 151 16Q138 -11 108 -11Q95 -11 87 -5T76 7T74 17Q74 30 112 181Q151 335 151 342Q154 357 154 369Q154 405 129 405Q107 405 92 377T69 316T57 280Q55 278 41 278H27Q21 284 21 287Z"></path></g></g></g></svg></mjx-container>)。</p> -<p>逃逸的 H2O 分子并非直线升空,而是在空气分子碰撞下进行三维随机游走。<br>根据爱因斯坦-斯托克斯方程,其扩散系数 <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.566ex;" xmlns="http://www.w3.org/2000/svg" width="16.19ex" height="2.452ex" role="img" focusable="false" viewBox="0 -833.9 7156.1 1083.9"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="mi"><path data-c="1D437" d="M287 628Q287 635 230 637Q207 637 200 638T193 647Q193 655 197 667T204 682Q206 683 403 683Q570 682 590 682T630 676Q702 659 752 597T803 431Q803 275 696 151T444 3L430 1L236 0H125H72Q48 0 41 2T33 11Q33 13 36 25Q40 41 44 43T67 46Q94 46 127 49Q141 52 146 61Q149 65 218 339T287 628ZM703 469Q703 507 692 537T666 584T629 613T590 629T555 636Q553 636 541 636T512 636T479 637H436Q392 637 386 627Q384 623 313 339T242 52Q242 48 253 48T330 47Q335 47 349 47T373 46Q499 46 581 128Q617 164 640 212T683 339T703 469Z"></path></g><g data-mml-node="mo" transform="translate(1105.8,0)"><path data-c="2248" d="M55 319Q55 360 72 393T114 444T163 472T205 482Q207 482 213 482T223 483Q262 483 296 468T393 413L443 381Q502 346 553 346Q609 346 649 375T694 454Q694 465 698 474T708 483Q722 483 722 452Q722 386 675 338T555 289Q514 289 468 310T388 357T308 404T224 426Q164 426 125 393T83 318Q81 289 69 289Q55 289 55 319ZM55 85Q55 126 72 159T114 210T163 238T205 248Q207 248 213 248T223 249Q262 249 296 234T393 179L443 147Q502 112 553 112Q609 112 649 141T694 220Q694 249 708 249T722 217Q722 153 675 104T555 55Q514 55 468 76T388 123T308 170T224 192Q164 192 125 159T83 84Q80 55 69 55Q55 55 55 85Z"></path></g><g data-mml-node="mn" transform="translate(2161.6,0)"><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z"></path><path data-c="2E" d="M78 60Q78 84 95 102T138 120Q162 120 180 104T199 61Q199 36 182 18T139 0T96 17T78 60Z" transform="translate(500,0)"></path><path data-c="32" d="M109 429Q82 429 66 447T50 491Q50 562 103 614T235 666Q326 666 387 610T449 465Q449 422 429 383T381 315T301 241Q265 210 201 149L142 93L218 92Q375 92 385 97Q392 99 409 186V189H449V186Q448 183 436 95T421 3V0H50V19V31Q50 38 56 46T86 81Q115 113 136 137Q145 147 170 174T204 211T233 244T261 278T284 308T305 340T320 369T333 401T340 431T343 464Q343 527 309 573T212 619Q179 619 154 602T119 569T109 550Q109 549 114 549Q132 549 151 535T170 489Q170 464 154 447T109 429Z" transform="translate(778,0)"></path><path data-c="38" d="M70 417T70 494T124 618T248 666Q319 666 374 624T429 515Q429 485 418 459T392 417T361 389T335 371T324 363L338 354Q352 344 366 334T382 323Q457 264 457 174Q457 95 399 37T249 -22Q159 -22 101 29T43 155Q43 263 172 335L154 348Q133 361 127 368Q70 417 70 494ZM286 386L292 390Q298 394 301 396T311 403T323 413T334 425T345 438T355 454T364 471T369 491T371 513Q371 556 342 586T275 624Q268 625 242 625Q201 625 165 599T128 534Q128 511 141 492T167 463T217 431Q224 426 228 424L286 386ZM250 21Q308 21 350 55T392 137Q392 154 387 169T375 194T353 216T330 234T301 253T274 270Q260 279 244 289T218 306L210 311Q204 311 181 294T133 239T107 157Q107 98 150 60T250 21Z" transform="translate(1278,0)"></path><path data-c="32" d="M109 429Q82 429 66 447T50 491Q50 562 103 614T235 666Q326 666 387 610T449 465Q449 422 429 383T381 315T301 241Q265 210 201 149L142 93L218 92Q375 92 385 97Q392 99 409 186V189H449V186Q448 183 436 95T421 3V0H50V19V31Q50 38 56 46T86 81Q115 113 136 137Q145 147 170 174T204 211T233 244T261 278T284 308T305 340T320 369T333 401T340 431T343 464Q343 527 309 573T212 619Q179 619 154 602T119 569T109 550Q109 549 114 549Q132 549 151 535T170 489Q170 464 154 447T109 429Z" transform="translate(1778,0)"></path></g><g data-mml-node="mi" transform="translate(4439.6,0)"><path data-c="1D450" d="M34 159Q34 268 120 355T306 442Q362 442 394 418T427 355Q427 326 408 306T360 285Q341 285 330 295T319 325T330 359T352 380T366 386H367Q367 388 361 392T340 400T306 404Q276 404 249 390Q228 381 206 359Q162 315 142 235T121 119Q121 73 147 50Q169 26 205 26H209Q321 26 394 111Q403 121 406 121Q410 121 419 112T429 98T420 83T391 55T346 25T282 0T202 -11Q127 -11 81 37T34 159Z"></path></g><g data-mml-node="msup" transform="translate(4872.6,0)"><g data-mml-node="mi"><path data-c="1D45A" d="M21 287Q22 293 24 303T36 341T56 388T88 425T132 442T175 435T205 417T221 395T229 376L231 369Q231 367 232 367L243 378Q303 442 384 442Q401 442 415 440T441 433T460 423T475 411T485 398T493 385T497 373T500 364T502 357L510 367Q573 442 659 442Q713 442 746 415T780 336Q780 285 742 178T704 50Q705 36 709 31T724 26Q752 26 776 56T815 138Q818 149 821 151T837 153Q857 153 857 145Q857 144 853 130Q845 101 831 73T785 17T716 -10Q669 -10 648 17T627 73Q627 92 663 193T700 345Q700 404 656 404H651Q565 404 506 303L499 291L466 157Q433 26 428 16Q415 -11 385 -11Q372 -11 364 -4T353 8T350 18Q350 29 384 161L420 307Q423 322 423 345Q423 404 379 404H374Q288 404 229 303L222 291L189 157Q156 26 151 16Q138 -11 108 -11Q95 -11 87 -5T76 7T74 17Q74 30 112 181Q151 335 151 342Q154 357 154 369Q154 405 129 405Q107 405 92 377T69 316T57 280Q55 278 41 278H27Q21 284 21 287Z"></path></g><g data-mml-node="mn" transform="translate(911,363) scale(0.707)"><path data-c="32" d="M109 429Q82 429 66 447T50 491Q50 562 103 614T235 666Q326 666 387 610T449 465Q449 422 429 383T381 315T301 241Q265 210 201 149L142 93L218 92Q375 92 385 97Q392 99 409 186V189H449V186Q448 183 436 95T421 3V0H50V19V31Q50 38 56 46T86 81Q115 113 136 137Q145 147 170 174T204 211T233 244T261 278T284 308T305 340T320 369T333 401T340 431T343 464Q343 527 309 573T212 619Q179 619 154 602T119 569T109 550Q109 549 114 549Q132 549 151 535T170 489Q170 464 154 447T109 429Z"></path></g></g><g data-mml-node="TeXAtom" data-mjx-texclass="ORD" transform="translate(6187.1,0)"><g data-mml-node="mo"><path data-c="2F" d="M423 750Q432 750 438 744T444 730Q444 725 271 248T92 -240Q85 -250 75 -250Q68 -250 62 -245T56 -231Q56 -221 230 257T407 740Q411 750 423 750Z"></path></g></g><g data-mml-node="mi" transform="translate(6687.1,0)"><path data-c="1D460" d="M131 289Q131 321 147 354T203 415T300 442Q362 442 390 415T419 355Q419 323 402 308T364 292Q351 292 340 300T328 326Q328 342 337 354T354 372T367 378Q368 378 368 379Q368 382 361 388T336 399T297 405Q249 405 227 379T204 326Q204 301 223 291T278 274T330 259Q396 230 396 163Q396 135 385 107T352 51T289 7T195 -10Q118 -10 86 19T53 87Q53 126 74 143T118 160Q133 160 146 151T160 120Q160 94 142 76T111 58Q109 57 108 57T107 55Q108 52 115 47T146 34T201 27Q237 27 263 38T301 66T318 97T323 122Q323 150 302 164T254 181T195 196T148 231Q131 256 131 289Z"></path></g></g></g></svg></mjx-container>(25℃标准大气压)。这意味着单个水分子在1秒内将形成半径约 <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.025ex;" xmlns="http://www.w3.org/2000/svg" width="6.864ex" height="1.557ex" role="img" focusable="false" viewBox="0 -677 3034 688"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="mn"><path data-c="32" d="M109 429Q82 429 66 447T50 491Q50 562 103 614T235 666Q326 666 387 610T449 465Q449 422 429 383T381 315T301 241Q265 210 201 149L142 93L218 92Q375 92 385 97Q392 99 409 186V189H449V186Q448 183 436 95T421 3V0H50V19V31Q50 38 56 46T86 81Q115 113 136 137Q145 147 170 174T204 211T233 244T261 278T284 308T305 340T320 369T333 401T340 431T343 464Q343 527 309 573T212 619Q179 619 154 602T119 569T109 550Q109 549 114 549Q132 549 151 535T170 489Q170 464 154 447T109 429Z"></path><path data-c="2E" d="M78 60Q78 84 95 102T138 120Q162 120 180 104T199 61Q199 36 182 18T139 0T96 17T78 60Z" transform="translate(500,0)"></path><path data-c="34" d="M462 0Q444 3 333 3Q217 3 199 0H190V46H221Q241 46 248 46T265 48T279 53T286 61Q287 63 287 115V165H28V211L179 442Q332 674 334 675Q336 677 355 677H373L379 671V211H471V165H379V114Q379 73 379 66T385 54Q393 47 442 46H471V0H462ZM293 211V545L74 212L183 211H293Z" transform="translate(778,0)"></path></g><g data-mml-node="mi" transform="translate(1278,0)"><path data-c="1D45A" d="M21 287Q22 293 24 303T36 341T56 388T88 425T132 442T175 435T205 417T221 395T229 376L231 369Q231 367 232 367L243 378Q303 442 384 442Q401 442 415 440T441 433T460 423T475 411T485 398T493 385T497 373T500 364T502 357L510 367Q573 442 659 442Q713 442 746 415T780 336Q780 285 742 178T704 50Q705 36 709 31T724 26Q752 26 776 56T815 138Q818 149 821 151T837 153Q857 153 857 145Q857 144 853 130Q845 101 831 73T785 17T716 -10Q669 -10 648 17T627 73Q627 92 663 193T700 345Q700 404 656 404H651Q565 404 506 303L499 291L466 157Q433 26 428 16Q415 -11 385 -11Q372 -11 364 -4T353 8T350 18Q350 29 384 161L420 307Q423 322 423 345Q423 404 379 404H374Q288 404 229 303L222 291L189 157Q156 26 151 16Q138 -11 108 -11Q95 -11 87 -5T76 7T74 17Q74 30 112 181Q151 335 151 342Q154 357 154 369Q154 405 129 405Q107 405 92 377T69 316T57 280Q55 278 41 278H27Q21 284 21 287Z"></path></g><g data-mml-node="mi" transform="translate(2156,0)"><path data-c="1D45A" d="M21 287Q22 293 24 303T36 341T56 388T88 425T132 442T175 435T205 417T221 395T229 376L231 369Q231 367 232 367L243 378Q303 442 384 442Q401 442 415 440T441 433T460 423T475 411T485 398T493 385T497 373T500 364T502 357L510 367Q573 442 659 442Q713 442 746 415T780 336Q780 285 742 178T704 50Q705 36 709 31T724 26Q752 26 776 56T815 138Q818 149 821 151T837 153Q857 153 857 145Q857 144 853 130Q845 101 831 73T785 17T716 -10Q669 -10 648 17T627 73Q627 92 663 193T700 345Q700 404 656 404H651Q565 404 506 303L499 291L466 157Q433 26 428 16Q415 -11 385 -11Q372 -11 364 -4T353 8T350 18Q350 29 384 161L420 307Q423 322 423 345Q423 404 379 404H374Q288 404 229 303L222 291L189 157Q156 26 151 16Q138 -11 108 -11Q95 -11 87 -5T76 7T74 17Q74 30 112 181Q151 335 151 342Q154 357 154 369Q154 405 129 405Q107 405 92 377T69 316T57 280Q55 278 41 278H27Q21 284 21 287Z"></path></g></g></g></svg></mjx-container> 的概率云,与数十亿同伴共同形成水汽。</p> +<p>当晨光加热露珠表面至 <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.489ex;" xmlns="http://www.w3.org/2000/svg" width="6.242ex" height="1.995ex" role="img" focusable="false" viewBox="0 -666 2759 882"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="mn"><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z"></path><path data-c="2E" d="M78 60Q78 84 95 102T138 120Q162 120 180 104T199 61Q199 36 182 18T139 0T96 17T78 60Z" transform="translate(500,0)"></path><path data-c="31" d="M213 578L200 573Q186 568 160 563T102 556H83V602H102Q149 604 189 617T245 641T273 663Q275 666 285 666Q294 666 302 660V361L303 61Q310 54 315 52T339 48T401 46H427V0H416Q395 3 257 3Q121 3 100 0H88V46H114Q136 46 152 46T177 47T193 50T201 52T207 57T213 61V578Z" transform="translate(778,0)"></path></g><g data-mml-node="mi" transform="translate(1278,0)"><path data-c="1D707" d="M58 -216Q44 -216 34 -208T23 -186Q23 -176 96 116T173 414Q186 442 219 442Q231 441 239 435T249 423T251 413Q251 401 220 279T187 142Q185 131 185 107V99Q185 26 252 26Q261 26 270 27T287 31T302 38T315 45T327 55T338 65T348 77T356 88T365 100L372 110L408 253Q444 395 448 404Q461 431 491 431Q504 431 512 424T523 412T525 402L449 84Q448 79 448 68Q448 43 455 35T476 26Q485 27 496 35Q517 55 537 131Q543 151 547 152Q549 153 557 153H561Q580 153 580 144Q580 138 575 117T555 63T523 13Q510 0 491 -8Q483 -10 467 -10Q446 -10 429 -4T402 11T385 29T376 44T374 51L368 45Q362 39 350 30T324 12T288 -4T246 -11Q199 -11 153 12L129 -85Q108 -167 104 -180T92 -202Q76 -216 58 -216Z"></path></g><g data-mml-node="mi" transform="translate(1881,0)"><path data-c="1D45A" d="M21 287Q22 293 24 303T36 341T56 388T88 425T132 442T175 435T205 417T221 395T229 376L231 369Q231 367 232 367L243 378Q303 442 384 442Q401 442 415 440T441 433T460 423T475 411T485 398T493 385T497 373T500 364T502 357L510 367Q573 442 659 442Q713 442 746 415T780 336Q780 285 742 178T704 50Q705 36 709 31T724 26Q752 26 776 56T815 138Q818 149 821 151T837 153Q857 153 857 145Q857 144 853 130Q845 101 831 73T785 17T716 -10Q669 -10 648 17T627 73Q627 92 663 193T700 345Q700 404 656 404H651Q565 404 506 303L499 291L466 157Q433 26 428 16Q415 -11 385 -11Q372 -11 364 -4T353 8T350 18Q350 29 384 161L420 307Q423 322 423 345Q423 404 379 404H374Q288 404 229 303L222 291L189 157Q156 26 151 16Q138 -11 108 -11Q95 -11 87 -5T76 7T74 17Q74 30 112 181Q151 335 151 342Q154 357 154 369Q154 405 129 405Q107 405 92 377T69 316T57 280Q55 278 41 278H27Q21 284 21 287Z"></path></g></g></g></svg></mjx-container> 深度时,表层水分子动能突破氢键束缚(键能约 <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.566ex;" xmlns="http://www.w3.org/2000/svg" width="9.762ex" height="2.262ex" role="img" focusable="false" viewBox="0 -750 4315 1000"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="mn"><path data-c="32" d="M109 429Q82 429 66 447T50 491Q50 562 103 614T235 666Q326 666 387 610T449 465Q449 422 429 383T381 315T301 241Q265 210 201 149L142 93L218 92Q375 92 385 97Q392 99 409 186V189H449V186Q448 183 436 95T421 3V0H50V19V31Q50 38 56 46T86 81Q115 113 136 137Q145 147 170 174T204 211T233 244T261 278T284 308T305 340T320 369T333 401T340 431T343 464Q343 527 309 573T212 619Q179 619 154 602T119 569T109 550Q109 549 114 549Q132 549 151 535T170 489Q170 464 154 447T109 429Z"></path><path data-c="33" d="M127 463Q100 463 85 480T69 524Q69 579 117 622T233 665Q268 665 277 664Q351 652 390 611T430 522Q430 470 396 421T302 350L299 348Q299 347 308 345T337 336T375 315Q457 262 457 175Q457 96 395 37T238 -22Q158 -22 100 21T42 130Q42 158 60 175T105 193Q133 193 151 175T169 130Q169 119 166 110T159 94T148 82T136 74T126 70T118 67L114 66Q165 21 238 21Q293 21 321 74Q338 107 338 175V195Q338 290 274 322Q259 328 213 329L171 330L168 332Q166 335 166 348Q166 366 174 366Q202 366 232 371Q266 376 294 413T322 525V533Q322 590 287 612Q265 626 240 626Q208 626 181 615T143 592T132 580H135Q138 579 143 578T153 573T165 566T175 555T183 540T186 520Q186 498 172 481T127 463Z" transform="translate(500,0)"></path></g><g data-mml-node="mi" transform="translate(1000,0)"><path data-c="1D458" d="M121 647Q121 657 125 670T137 683Q138 683 209 688T282 694Q294 694 294 686Q294 679 244 477Q194 279 194 272Q213 282 223 291Q247 309 292 354T362 415Q402 442 438 442Q468 442 485 423T503 369Q503 344 496 327T477 302T456 291T438 288Q418 288 406 299T394 328Q394 353 410 369T442 390L458 393Q446 405 434 405H430Q398 402 367 380T294 316T228 255Q230 254 243 252T267 246T293 238T320 224T342 206T359 180T365 147Q365 130 360 106T354 66Q354 26 381 26Q429 26 459 145Q461 153 479 153H483Q499 153 499 144Q499 139 496 130Q455 -11 378 -11Q333 -11 305 15T277 90Q277 108 280 121T283 145Q283 167 269 183T234 206T200 217T182 220H180Q168 178 159 139T145 81T136 44T129 20T122 7T111 -2Q98 -11 83 -11Q66 -11 57 -1T48 16Q48 26 85 176T158 471L195 616Q196 629 188 632T149 637H144Q134 637 131 637T124 640T121 647Z"></path></g><g data-mml-node="mi" transform="translate(1521,0)"><path data-c="1D43D" d="M447 625Q447 637 354 637H329Q323 642 323 645T325 664Q329 677 335 683H352Q393 681 498 681Q541 681 568 681T605 682T619 682Q633 682 633 672Q633 670 630 658Q626 642 623 640T604 637Q552 637 545 623Q541 610 483 376Q420 128 419 127Q397 64 333 21T195 -22Q137 -22 97 8T57 88Q57 130 80 152T132 174Q177 174 182 130Q182 98 164 80T123 56Q115 54 115 53T122 44Q148 15 197 15Q235 15 271 47T324 130Q328 142 387 380T447 625Z"></path></g><g data-mml-node="TeXAtom" data-mjx-texclass="ORD" transform="translate(2154,0)"><g data-mml-node="mo"><path data-c="2F" d="M423 750Q432 750 438 744T444 730Q444 725 271 248T92 -240Q85 -250 75 -250Q68 -250 62 -245T56 -231Q56 -221 230 257T407 740Q411 750 423 750Z"></path></g></g><g data-mml-node="mi" transform="translate(2654,0)"><path data-c="1D45A" d="M21 287Q22 293 24 303T36 341T56 388T88 425T132 442T175 435T205 417T221 395T229 376L231 369Q231 367 232 367L243 378Q303 442 384 442Q401 442 415 440T441 433T460 423T475 411T485 398T493 385T497 373T500 364T502 357L510 367Q573 442 659 442Q713 442 746 415T780 336Q780 285 742 178T704 50Q705 36 709 31T724 26Q752 26 776 56T815 138Q818 149 821 151T837 153Q857 153 857 145Q857 144 853 130Q845 101 831 73T785 17T716 -10Q669 -10 648 17T627 73Q627 92 663 193T700 345Q700 404 656 404H651Q565 404 506 303L499 291L466 157Q433 26 428 16Q415 -11 385 -11Q372 -11 364 -4T353 8T350 18Q350 29 384 161L420 307Q423 322 423 345Q423 404 379 404H374Q288 404 229 303L222 291L189 157Q156 26 151 16Q138 -11 108 -11Q95 -11 87 -5T76 7T74 17Q74 30 112 181Q151 335 151 342Q154 357 154 369Q154 405 129 405Q107 405 92 377T69 316T57 280Q55 278 41 278H27Q21 284 21 287Z"></path></g><g data-mml-node="mi" transform="translate(3532,0)"><path data-c="1D45C" d="M201 -11Q126 -11 80 38T34 156Q34 221 64 279T146 380Q222 441 301 441Q333 441 341 440Q354 437 367 433T402 417T438 387T464 338T476 268Q476 161 390 75T201 -11ZM121 120Q121 70 147 48T206 26Q250 26 289 58T351 142Q360 163 374 216T388 308Q388 352 370 375Q346 405 306 405Q243 405 195 347Q158 303 140 230T121 120Z"></path></g><g data-mml-node="mi" transform="translate(4017,0)"><path data-c="1D459" d="M117 59Q117 26 142 26Q179 26 205 131Q211 151 215 152Q217 153 225 153H229Q238 153 241 153T246 151T248 144Q247 138 245 128T234 90T214 43T183 6T137 -11Q101 -11 70 11T38 85Q38 97 39 102L104 360Q167 615 167 623Q167 626 166 628T162 632T157 634T149 635T141 636T132 637T122 637Q112 637 109 637T101 638T95 641T94 647Q94 649 96 661Q101 680 107 682T179 688Q194 689 213 690T243 693T254 694Q266 694 266 686Q266 675 193 386T118 83Q118 81 118 75T117 65V59Z"></path></g></g></g></svg></mjx-container>)。<br> +这种相变并非整齐划一的队列解散,而是呈现量子隧穿效应——单个水分子以 <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.05ex;" xmlns="http://www.w3.org/2000/svg" width="6.356ex" height="2.005ex" role="img" focusable="false" viewBox="0 -864 2809.2 886"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="msup"><g data-mml-node="mn"><path data-c="31" d="M213 578L200 573Q186 568 160 563T102 556H83V602H102Q149 604 189 617T245 641T273 663Q275 666 285 666Q294 666 302 660V361L303 61Q310 54 315 52T339 48T401 46H427V0H416Q395 3 257 3Q121 3 100 0H88V46H114Q136 46 152 46T177 47T193 50T201 52T207 57T213 61V578Z"></path><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z" transform="translate(500,0)"></path></g><g data-mml-node="TeXAtom" transform="translate(1033,393.1) scale(0.707)" data-mjx-texclass="ORD"><g data-mml-node="mo"><path data-c="2212" d="M84 237T84 250T98 270H679Q694 262 694 250T679 230H98Q84 237 84 250Z"></path></g><g data-mml-node="mn" transform="translate(778,0)"><path data-c="31" d="M213 578L200 573Q186 568 160 563T102 556H83V602H102Q149 604 189 617T245 641T273 663Q275 666 285 666Q294 666 302 660V361L303 61Q310 54 315 52T339 48T401 46H427V0H416Q395 3 257 3Q121 3 100 0H88V46H114Q136 46 152 46T177 47T193 50T201 52T207 57T213 61V578Z"></path><path data-c="32" d="M109 429Q82 429 66 447T50 491Q50 562 103 614T235 666Q326 666 387 610T449 465Q449 422 429 383T381 315T301 241Q265 210 201 149L142 93L218 92Q375 92 385 97Q392 99 409 186V189H449V186Q448 183 436 95T421 3V0H50V19V31Q50 38 56 46T86 81Q115 113 136 137Q145 147 170 174T204 211T233 244T261 278T284 308T305 340T320 369T333 401T340 431T343 464Q343 527 309 573T212 619Q179 619 154 602T119 569T109 550Q109 549 114 549Q132 549 151 535T170 489Q170 464 154 447T109 429Z" transform="translate(500,0)"></path></g></g></g><g data-mml-node="mi" transform="translate(2340.2,0)"><path data-c="1D460" d="M131 289Q131 321 147 354T203 415T300 442Q362 442 390 415T419 355Q419 323 402 308T364 292Q351 292 340 300T328 326Q328 342 337 354T354 372T367 378Q368 378 368 379Q368 382 361 388T336 399T297 405Q249 405 227 379T204 326Q204 301 223 291T278 274T330 259Q396 230 396 163Q396 135 385 107T352 51T289 7T195 -10Q118 -10 86 19T53 87Q53 126 74 143T118 160Q133 160 146 151T160 120Q160 94 142 76T111 58Q109 57 108 57T107 55Q108 52 115 47T146 34T201 27Q237 27 263 38T301 66T318 97T323 122Q323 150 302 164T254 181T195 196T148 231Q131 256 131 289Z"></path></g></g></g></svg></mjx-container> 量级的涨落,在液态与气态间振荡,直到完全脱离范德华力作用半径(约 <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.05ex;" xmlns="http://www.w3.org/2000/svg" width="6.235ex" height="1.557ex" role="img" focusable="false" viewBox="0 -666 2756 688"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="mn"><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z"></path><path data-c="2E" d="M78 60Q78 84 95 102T138 120Q162 120 180 104T199 61Q199 36 182 18T139 0T96 17T78 60Z" transform="translate(500,0)"></path><path data-c="33" d="M127 463Q100 463 85 480T69 524Q69 579 117 622T233 665Q268 665 277 664Q351 652 390 611T430 522Q430 470 396 421T302 350L299 348Q299 347 308 345T337 336T375 315Q457 262 457 175Q457 96 395 37T238 -22Q158 -22 100 21T42 130Q42 158 60 175T105 193Q133 193 151 175T169 130Q169 119 166 110T159 94T148 82T136 74T126 70T118 67L114 66Q165 21 238 21Q293 21 321 74Q338 107 338 175V195Q338 290 274 322Q259 328 213 329L171 330L168 332Q166 335 166 348Q166 366 174 366Q202 366 232 371Q266 376 294 413T322 525V533Q322 590 287 612Q265 626 240 626Q208 626 181 615T143 592T132 580H135Q138 579 143 578T153 573T165 566T175 555T183 540T186 520Q186 498 172 481T127 463Z" transform="translate(778,0)"></path></g><g data-mml-node="mi" transform="translate(1278,0)"><path data-c="1D45B" d="M21 287Q22 293 24 303T36 341T56 388T89 425T135 442Q171 442 195 424T225 390T231 369Q231 367 232 367L243 378Q304 442 382 442Q436 442 469 415T503 336T465 179T427 52Q427 26 444 26Q450 26 453 27Q482 32 505 65T540 145Q542 153 560 153Q580 153 580 145Q580 144 576 130Q568 101 554 73T508 17T439 -10Q392 -10 371 17T350 73Q350 92 386 193T423 345Q423 404 379 404H374Q288 404 229 303L222 291L189 157Q156 26 151 16Q138 -11 108 -11Q95 -11 87 -5T76 7T74 17Q74 30 112 180T152 343Q153 348 153 366Q153 405 129 405Q91 405 66 305Q60 285 60 284Q58 278 41 278H27Q21 284 21 287Z"></path></g><g data-mml-node="mi" transform="translate(1878,0)"><path data-c="1D45A" d="M21 287Q22 293 24 303T36 341T56 388T88 425T132 442T175 435T205 417T221 395T229 376L231 369Q231 367 232 367L243 378Q303 442 384 442Q401 442 415 440T441 433T460 423T475 411T485 398T493 385T497 373T500 364T502 357L510 367Q573 442 659 442Q713 442 746 415T780 336Q780 285 742 178T704 50Q705 36 709 31T724 26Q752 26 776 56T815 138Q818 149 821 151T837 153Q857 153 857 145Q857 144 853 130Q845 101 831 73T785 17T716 -10Q669 -10 648 17T627 73Q627 92 663 193T700 345Q700 404 656 404H651Q565 404 506 303L499 291L466 157Q433 26 428 16Q415 -11 385 -11Q372 -11 364 -4T353 8T350 18Q350 29 384 161L420 307Q423 322 423 345Q423 404 379 404H374Q288 404 229 303L222 291L189 157Q156 26 151 16Q138 -11 108 -11Q95 -11 87 -5T76 7T74 17Q74 30 112 181Q151 335 151 342Q154 357 154 369Q154 405 129 405Q107 405 92 377T69 316T57 280Q55 278 41 278H27Q21 284 21 287Z"></path></g></g></g></svg></mjx-container>)。</p> +<p>逃逸的 H2O 分子并非直线升空,而是在空气分子碰撞下进行三维随机游走。<br> +根据爱因斯坦-斯托克斯方程,其扩散系数 <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.566ex;" xmlns="http://www.w3.org/2000/svg" width="16.19ex" height="2.452ex" role="img" focusable="false" viewBox="0 -833.9 7156.1 1083.9"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="mi"><path data-c="1D437" d="M287 628Q287 635 230 637Q207 637 200 638T193 647Q193 655 197 667T204 682Q206 683 403 683Q570 682 590 682T630 676Q702 659 752 597T803 431Q803 275 696 151T444 3L430 1L236 0H125H72Q48 0 41 2T33 11Q33 13 36 25Q40 41 44 43T67 46Q94 46 127 49Q141 52 146 61Q149 65 218 339T287 628ZM703 469Q703 507 692 537T666 584T629 613T590 629T555 636Q553 636 541 636T512 636T479 637H436Q392 637 386 627Q384 623 313 339T242 52Q242 48 253 48T330 47Q335 47 349 47T373 46Q499 46 581 128Q617 164 640 212T683 339T703 469Z"></path></g><g data-mml-node="mo" transform="translate(1105.8,0)"><path data-c="2248" d="M55 319Q55 360 72 393T114 444T163 472T205 482Q207 482 213 482T223 483Q262 483 296 468T393 413L443 381Q502 346 553 346Q609 346 649 375T694 454Q694 465 698 474T708 483Q722 483 722 452Q722 386 675 338T555 289Q514 289 468 310T388 357T308 404T224 426Q164 426 125 393T83 318Q81 289 69 289Q55 289 55 319ZM55 85Q55 126 72 159T114 210T163 238T205 248Q207 248 213 248T223 249Q262 249 296 234T393 179L443 147Q502 112 553 112Q609 112 649 141T694 220Q694 249 708 249T722 217Q722 153 675 104T555 55Q514 55 468 76T388 123T308 170T224 192Q164 192 125 159T83 84Q80 55 69 55Q55 55 55 85Z"></path></g><g data-mml-node="mn" transform="translate(2161.6,0)"><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z"></path><path data-c="2E" d="M78 60Q78 84 95 102T138 120Q162 120 180 104T199 61Q199 36 182 18T139 0T96 17T78 60Z" transform="translate(500,0)"></path><path data-c="32" d="M109 429Q82 429 66 447T50 491Q50 562 103 614T235 666Q326 666 387 610T449 465Q449 422 429 383T381 315T301 241Q265 210 201 149L142 93L218 92Q375 92 385 97Q392 99 409 186V189H449V186Q448 183 436 95T421 3V0H50V19V31Q50 38 56 46T86 81Q115 113 136 137Q145 147 170 174T204 211T233 244T261 278T284 308T305 340T320 369T333 401T340 431T343 464Q343 527 309 573T212 619Q179 619 154 602T119 569T109 550Q109 549 114 549Q132 549 151 535T170 489Q170 464 154 447T109 429Z" transform="translate(778,0)"></path><path data-c="38" d="M70 417T70 494T124 618T248 666Q319 666 374 624T429 515Q429 485 418 459T392 417T361 389T335 371T324 363L338 354Q352 344 366 334T382 323Q457 264 457 174Q457 95 399 37T249 -22Q159 -22 101 29T43 155Q43 263 172 335L154 348Q133 361 127 368Q70 417 70 494ZM286 386L292 390Q298 394 301 396T311 403T323 413T334 425T345 438T355 454T364 471T369 491T371 513Q371 556 342 586T275 624Q268 625 242 625Q201 625 165 599T128 534Q128 511 141 492T167 463T217 431Q224 426 228 424L286 386ZM250 21Q308 21 350 55T392 137Q392 154 387 169T375 194T353 216T330 234T301 253T274 270Q260 279 244 289T218 306L210 311Q204 311 181 294T133 239T107 157Q107 98 150 60T250 21Z" transform="translate(1278,0)"></path><path data-c="32" d="M109 429Q82 429 66 447T50 491Q50 562 103 614T235 666Q326 666 387 610T449 465Q449 422 429 383T381 315T301 241Q265 210 201 149L142 93L218 92Q375 92 385 97Q392 99 409 186V189H449V186Q448 183 436 95T421 3V0H50V19V31Q50 38 56 46T86 81Q115 113 136 137Q145 147 170 174T204 211T233 244T261 278T284 308T305 340T320 369T333 401T340 431T343 464Q343 527 309 573T212 619Q179 619 154 602T119 569T109 550Q109 549 114 549Q132 549 151 535T170 489Q170 464 154 447T109 429Z" transform="translate(1778,0)"></path></g><g data-mml-node="mi" transform="translate(4439.6,0)"><path data-c="1D450" d="M34 159Q34 268 120 355T306 442Q362 442 394 418T427 355Q427 326 408 306T360 285Q341 285 330 295T319 325T330 359T352 380T366 386H367Q367 388 361 392T340 400T306 404Q276 404 249 390Q228 381 206 359Q162 315 142 235T121 119Q121 73 147 50Q169 26 205 26H209Q321 26 394 111Q403 121 406 121Q410 121 419 112T429 98T420 83T391 55T346 25T282 0T202 -11Q127 -11 81 37T34 159Z"></path></g><g data-mml-node="msup" transform="translate(4872.6,0)"><g data-mml-node="mi"><path data-c="1D45A" d="M21 287Q22 293 24 303T36 341T56 388T88 425T132 442T175 435T205 417T221 395T229 376L231 369Q231 367 232 367L243 378Q303 442 384 442Q401 442 415 440T441 433T460 423T475 411T485 398T493 385T497 373T500 364T502 357L510 367Q573 442 659 442Q713 442 746 415T780 336Q780 285 742 178T704 50Q705 36 709 31T724 26Q752 26 776 56T815 138Q818 149 821 151T837 153Q857 153 857 145Q857 144 853 130Q845 101 831 73T785 17T716 -10Q669 -10 648 17T627 73Q627 92 663 193T700 345Q700 404 656 404H651Q565 404 506 303L499 291L466 157Q433 26 428 16Q415 -11 385 -11Q372 -11 364 -4T353 8T350 18Q350 29 384 161L420 307Q423 322 423 345Q423 404 379 404H374Q288 404 229 303L222 291L189 157Q156 26 151 16Q138 -11 108 -11Q95 -11 87 -5T76 7T74 17Q74 30 112 181Q151 335 151 342Q154 357 154 369Q154 405 129 405Q107 405 92 377T69 316T57 280Q55 278 41 278H27Q21 284 21 287Z"></path></g><g data-mml-node="mn" transform="translate(911,363) scale(0.707)"><path data-c="32" d="M109 429Q82 429 66 447T50 491Q50 562 103 614T235 666Q326 666 387 610T449 465Q449 422 429 383T381 315T301 241Q265 210 201 149L142 93L218 92Q375 92 385 97Q392 99 409 186V189H449V186Q448 183 436 95T421 3V0H50V19V31Q50 38 56 46T86 81Q115 113 136 137Q145 147 170 174T204 211T233 244T261 278T284 308T305 340T320 369T333 401T340 431T343 464Q343 527 309 573T212 619Q179 619 154 602T119 569T109 550Q109 549 114 549Q132 549 151 535T170 489Q170 464 154 447T109 429Z"></path></g></g><g data-mml-node="TeXAtom" data-mjx-texclass="ORD" transform="translate(6187.1,0)"><g data-mml-node="mo"><path data-c="2F" d="M423 750Q432 750 438 744T444 730Q444 725 271 248T92 -240Q85 -250 75 -250Q68 -250 62 -245T56 -231Q56 -221 230 257T407 740Q411 750 423 750Z"></path></g></g><g data-mml-node="mi" transform="translate(6687.1,0)"><path data-c="1D460" d="M131 289Q131 321 147 354T203 415T300 442Q362 442 390 415T419 355Q419 323 402 308T364 292Q351 292 340 300T328 326Q328 342 337 354T354 372T367 378Q368 378 368 379Q368 382 361 388T336 399T297 405Q249 405 227 379T204 326Q204 301 223 291T278 274T330 259Q396 230 396 163Q396 135 385 107T352 51T289 7T195 -10Q118 -10 86 19T53 87Q53 126 74 143T118 160Q133 160 146 151T160 120Q160 94 142 76T111 58Q109 57 108 57T107 55Q108 52 115 47T146 34T201 27Q237 27 263 38T301 66T318 97T323 122Q323 150 302 164T254 181T195 196T148 231Q131 256 131 289Z"></path></g></g></g></svg></mjx-container>(25℃标准大气压)。这意味着单个水分子在1秒内将形成半径约 <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.025ex;" xmlns="http://www.w3.org/2000/svg" width="6.864ex" height="1.557ex" role="img" focusable="false" viewBox="0 -677 3034 688"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="mn"><path data-c="32" d="M109 429Q82 429 66 447T50 491Q50 562 103 614T235 666Q326 666 387 610T449 465Q449 422 429 383T381 315T301 241Q265 210 201 149L142 93L218 92Q375 92 385 97Q392 99 409 186V189H449V186Q448 183 436 95T421 3V0H50V19V31Q50 38 56 46T86 81Q115 113 136 137Q145 147 170 174T204 211T233 244T261 278T284 308T305 340T320 369T333 401T340 431T343 464Q343 527 309 573T212 619Q179 619 154 602T119 569T109 550Q109 549 114 549Q132 549 151 535T170 489Q170 464 154 447T109 429Z"></path><path data-c="2E" d="M78 60Q78 84 95 102T138 120Q162 120 180 104T199 61Q199 36 182 18T139 0T96 17T78 60Z" transform="translate(500,0)"></path><path data-c="34" d="M462 0Q444 3 333 3Q217 3 199 0H190V46H221Q241 46 248 46T265 48T279 53T286 61Q287 63 287 115V165H28V211L179 442Q332 674 334 675Q336 677 355 677H373L379 671V211H471V165H379V114Q379 73 379 66T385 54Q393 47 442 46H471V0H462ZM293 211V545L74 212L183 211H293Z" transform="translate(778,0)"></path></g><g data-mml-node="mi" transform="translate(1278,0)"><path data-c="1D45A" d="M21 287Q22 293 24 303T36 341T56 388T88 425T132 442T175 435T205 417T221 395T229 376L231 369Q231 367 232 367L243 378Q303 442 384 442Q401 442 415 440T441 433T460 423T475 411T485 398T493 385T497 373T500 364T502 357L510 367Q573 442 659 442Q713 442 746 415T780 336Q780 285 742 178T704 50Q705 36 709 31T724 26Q752 26 776 56T815 138Q818 149 821 151T837 153Q857 153 857 145Q857 144 853 130Q845 101 831 73T785 17T716 -10Q669 -10 648 17T627 73Q627 92 663 193T700 345Q700 404 656 404H651Q565 404 506 303L499 291L466 157Q433 26 428 16Q415 -11 385 -11Q372 -11 364 -4T353 8T350 18Q350 29 384 161L420 307Q423 322 423 345Q423 404 379 404H374Q288 404 229 303L222 291L189 157Q156 26 151 16Q138 -11 108 -11Q95 -11 87 -5T76 7T74 17Q74 30 112 181Q151 335 151 342Q154 357 154 369Q154 405 129 405Q107 405 92 377T69 316T57 280Q55 278 41 278H27Q21 284 21 287Z"></path></g><g data-mml-node="mi" transform="translate(2156,0)"><path data-c="1D45A" d="M21 287Q22 293 24 303T36 341T56 388T88 425T132 442T175 435T205 417T221 395T229 376L231 369Q231 367 232 367L243 378Q303 442 384 442Q401 442 415 440T441 433T460 423T475 411T485 398T493 385T497 373T500 364T502 357L510 367Q573 442 659 442Q713 442 746 415T780 336Q780 285 742 178T704 50Q705 36 709 31T724 26Q752 26 776 56T815 138Q818 149 821 151T837 153Q857 153 857 145Q857 144 853 130Q845 101 831 73T785 17T716 -10Q669 -10 648 17T627 73Q627 92 663 193T700 345Q700 404 656 404H651Q565 404 506 303L499 291L466 157Q433 26 428 16Q415 -11 385 -11Q372 -11 364 -4T353 8T350 18Q350 29 384 161L420 307Q423 322 423 345Q423 404 379 404H374Q288 404 229 303L222 291L189 157Q156 26 151 16Q138 -11 108 -11Q95 -11 87 -5T76 7T74 17Q74 30 112 181Q151 335 151 342Q154 357 154 369Q154 405 129 405Q107 405 92 377T69 316T57 280Q55 278 41 278H27Q21 284 21 287Z"></path></g></g></g></svg></mjx-container> 的概率云,与数十亿同伴共同形成水汽。</p> <p>水中捞月,伸手时,涟漪碎了三千世界。</p> <p>人类的眉睫处有十方虚空,三藏经书不过指月之指,</p> <p>看见儿时门前溪水倒流,看见婴孩啼哭时眼底星河闪烁。</p> @@ -3429,12 +3728,13 @@ await prisma.$transaction(async tx => { <url>/2024/01/23/%E4%BA%8C%E3%80%87%E4%BA%8C%E5%9B%9B%E5%B9%B4%E4%B8%80%E6%9C%88%E4%BA%8C%E5%8D%81%E4%B8%89%E6%97%A5/</url> <content><![CDATA[<p>有人在桥上并肩走过,孩子们举着风车大笑着跑开,热乎乎的米糕新鲜出炉,香气混着夜风传去老远。</p> <p>桥上是喧闹繁杂的尘世万千,桥下是静谧安宁的人间留恋。</p> -<p>我有时候会无法控制的想,如果这一切都是梦,一觉醒来又回到了那暗无天日的日子……但转瞬即否定这个答案———那我会重新走到今天。</p> +<p>我有时候会无法控制的想,如果这一切都是梦,一觉醒来又回到了那暗无天日的日子…但转瞬即否定这个答案———那我会重新走到今天。</p> <p>寒风拂过我的侧脸,把碎发拂去耳后。</p> <p>如果你也只剩活着了。</p> <p>就像一条小鱼,在这一方小世界中摆尾流浪,海波荡漾了许多年,也飘出去那么远。</p> <p>这么些年的煎熬时光或许将你沉寂,或许掀起了惊涛骇浪,吞噬你的理智与晴空,令你彻底疯狂。</p> -<p>直到海浪卷起鱼群,波及到每一个地方,<br>直到风平浪静,晴空如洗。</p> +<p>直到海浪卷起鱼群,波及到每一个地方,<br> +直到风平浪静,晴空如洗。</p> <hr> <p>但几个小时之后,天际黎明乍现的那一瞬,会有一只无形的大手,将最后一层青灰色的夜幕轻轻抹去。</p> <p>晨光会从海平线迤逦而来,洒向鳞次栉比的高楼和错综复杂的街道。码头,树木,楼房,电线杆。</p> @@ -3457,12 +3757,18 @@ await prisma.$transaction(async tx => { <entry> <title>二〇二四年三月二十二日</title> <url>/2024/03/22/%E4%BA%8C%E3%80%87%E4%BA%8C%E5%9B%9B%E5%B9%B4%E4%B8%89%E6%9C%88%E4%BA%8C%E5%8D%81%E4%BA%8C%E6%97%A5/</url> - <content><![CDATA[<p>毛毛在人群中牵着我,却很难融入人群,我在林中面对着毛毛,树木的思想却千姿百态地向我涌来。<br>它说,它要将灵魂撕裂,让它暴露在最灼热的阳光下灼烧,要让风刺进来,硬生生扯开一道口子,要让原有的赤色消失殆尽,只留下一堆松散的灰色颗粒,任雨打浮萍。</p> -<p>毛毛和我看到了宇宙熵增,和我见到了熙攘的街道,现在变成了我耳边的风声。<br>是啊,是啊,你不再身陷囹圄,自由不再是攀在高墙上爬山虎的叶子,不再是吹进风间的花粉,不再是藏躲进阴暗土地里的水,不再是破碎割手的杯子片块。<br>但是这个世界还是越来越美了,我独自一人,却很自在,别无所求,只想被阳光晒透,被狂风穿过。渴望成熟,要准备好死去,也准备好重生。</p> + <content><![CDATA[<p>毛毛在人群中牵着我,却很难融入人群,我在林中面对着毛毛,树木的思想却千姿百态地向我涌来。<br> +它说,它要将灵魂撕裂,让它暴露在最灼热的阳光下灼烧,要让风刺进来,硬生生扯开一道口子,要让原有的赤色消失殆尽,只留下一堆松散的灰色颗粒,任雨打浮萍。</p> +<p>毛毛和我看到了宇宙熵增,和我见到了熙攘的街道,现在变成了我耳边的风声。<br> +是啊,是啊,你不再身陷囹圄,自由不再是攀在高墙上爬山虎的叶子,不再是吹进风间的花粉,不再是藏躲进阴暗土地里的水,不再是破碎割手的杯子片块。<br> +但是这个世界还是越来越美了,我独自一人,却很自在,别无所求,只想被阳光晒透,被狂风穿过。渴望成熟,要准备好死去,也准备好重生。</p> <hr> <p>小土堆上长出了狗尾巴草,当我靠近时,狗尾巴草会向我轻轻晃动,就像它小时候向我跑来时那样,不同的是,当我向前跑的时候,背后没有一个小小的身影再追过来了,但当我回望小土堆,狗尾巴草依然在摇晃,就像当初给予我回应那样。</p> <hr> -<p>狗儿要听狗儿歌,<br>毛毛下雨要回家,<br>小狗小狗画梅花,<br>直走就是我们家。</p> +<p>狗儿要听狗儿歌,<br> +毛毛下雨要回家,<br> +小狗小狗画梅花,<br> +直走就是我们家。</p> ]]></content> <categories> <category>gallery</category> @@ -3499,9 +3805,15 @@ await prisma.$transaction(async tx => { <entry> <title>二〇二四年二月七日</title> <url>/2024/02/07/%E4%BA%8C%E3%80%87%E4%BA%8C%E5%9B%9B%E5%B9%B4%E4%BA%8C%E6%9C%88%E4%B8%83%E6%97%A5/</url> - <content><![CDATA[<p>瀑布的水逆流而上,<br>蒲公英种子从远处飘回,聚成伞的模样,<br>太阳从西边升起,落向东方。</p> -<p>子弹退回枪膛,<br>运动员回到起跑线上,<br>我交回录取通知书,忘了十年寒窗。</p> -<p>厨房里飘来饭菜的香,<br>你把我的卷子签好名字,<br>关掉电视,帮我把书包背上。</p> + <content><![CDATA[<p>瀑布的水逆流而上,<br> +蒲公英种子从远处飘回,聚成伞的模样,<br> +太阳从西边升起,落向东方。</p> +<p>子弹退回枪膛,<br> +运动员回到起跑线上,<br> +我交回录取通知书,忘了十年寒窗。</p> +<p>厨房里飘来饭菜的香,<br> +你把我的卷子签好名字,<br> +关掉电视,帮我把书包背上。</p> <p>你还在我身旁。</p> <hr> <p>功利性主义总会引导我们思考结局,可生活本质上就是一场旅途。</p> @@ -3516,9 +3828,23 @@ await prisma.$transaction(async tx => { <entry> <title>二〇二四年五月七日</title> <url>/2024/05/07/%E4%BA%8C%E3%80%87%E4%BA%8C%E5%9B%9B%E5%B9%B4%E4%BA%94%E6%9C%88%E4%B8%83%E6%97%A5/</url> - <content><![CDATA[<p>我在写信<br>寄给羊水<br>信里提到<br>宇宙称呼它为灰<br>我们叫地球<br>还提到<br>风车不能骑<br>但是石头可以打水漂<br>你呀<br>到时别忘了<br>用小小的哭声款待我</p> + <content><![CDATA[<p>我在写信<br> +寄给羊水<br> +信里提到<br> +宇宙称呼它为灰<br> +我们叫地球<br> +还提到<br> +风车不能骑<br> +但是石头可以打水漂<br> +你呀<br> +到时别忘了<br> +用小小的哭声款待我</p> <hr> -<p>我们应该坐在一起发呆<br>发很久的呆<br>然后我说人类好无聊啊<br>这个地球完蛋了<br>你点点头</p> +<p>我们应该坐在一起发呆<br> +发很久的呆<br> +然后我说人类好无聊啊<br> +这个地球完蛋了<br> +你点点头</p> ]]></content> <categories> <category>gallery</category> @@ -3533,10 +3859,11 @@ await prisma.$transaction(async tx => { <p>多尝试点事情吧,试得越多,就能越快判断出自己是不是这块料。如果是,很好;如果不是,过,下一个。在这期间不要有任何心态波澜,行就是行,不行就是不行。反正不是非行不可。</p> <p>人自信不是样样精通、事事皆成,凡事都做得比别人更好;自信是一个高级陷阱,仰赖自信的人终有一日会崩塌于自信的毁灭。</p> <p>用生命力来取代往日的自信心,用绝对强大的权力意志来取代往日相对成功的小胜小利。</p> -<p>不放弃的理由不是因为自信,而是因为知道这事必须得干/行得通;放弃的理由也不是因为不自信,而是因为知道这事不能去干/行不通。</p> +<p>不放弃的理由不是因为自信,而是因为知道这事必须得干/行得通;放弃的理由也不是因为不自信,而是因为知道这事不能去干/行不通。</p> <p>而一旦在理性和感性层面都认为必须办成某件事,那就不顾一切去办成。哪怕绕再多的路,要办的事就是要办。</p> <p>当不再局限于自信或自卑,而是立足于实事求是去布局和行动,一切都会变得更加清晰明了。若想成事,首先要花时间去搞明白自己的长处与短板,然后学会在面对具体事项之际快速判断自己行不行、是不是非做不可、要做的话又有几分把握、失败了要如何应对、要不要改变其中某些变量再多试几次。</p> -<p>当有了一个目标,需要的不是豪言壮志,不是任何心理建设,而是尽快上手去做。<br>做一件事,无关心态,只要去做就是了。发挥最大的主观能动性,遇到问题就解决,碰到障碍就破开,需要帮助就求助。别因为所谓的自信就盲目冒进,也别因为所谓的自卑就胆小退缩,那俩玩意都不存在。</p> +<p>当有了一个目标,需要的不是豪言壮志,不是任何心理建设,而是尽快上手去做。<br> +做一件事,无关心态,只要去做就是了。发挥最大的主观能动性,遇到问题就解决,碰到障碍就破开,需要帮助就求助。别因为所谓的自信就盲目冒进,也别因为所谓的自卑就胆小退缩,那俩玩意都不存在。</p> <p>尊重事情本身的客观发展规律,什么样的人匹配什么样的事,什么样的条件匹配什么样的理想。别把心态想得太重要,更别花太多时间精力去建设心态,客观规律不会因为心态就发生奇迹般地转变。</p> <p>你最好趁早学会尊重客观规律。</p> ]]></content> @@ -3547,7 +3874,10 @@ await prisma.$transaction(async tx => { <entry> <title>二〇二四年八月一日</title> <url>/2024/08/02/%E4%BA%8C%E3%80%87%E4%BA%8C%E5%9B%9B%E5%B9%B4%E5%85%AB%E6%9C%88%E4%B8%80%E6%97%A5/</url> - <content><![CDATA[<p>阿公烧烟成老瘾,<br>阿公饮酒会面红,<br>他说日子要开心,<br>他说人生要尽兴。</p> + <content><![CDATA[<p>阿公烧烟成老瘾,<br> +阿公饮酒会面红,<br> +他说日子要开心,<br> +他说人生要尽兴。</p> ]]></content> <categories> <category>gallery</category> @@ -3556,7 +3886,11 @@ await prisma.$transaction(async tx => { <entry> <title>二〇二四年六月二十七日</title> <url>/2024/06/27/%E4%BA%8C%E3%80%87%E4%BA%8C%E5%9B%9B%E5%B9%B4%E5%85%AD%E6%9C%88%E4%BA%8C%E5%8D%81%E4%B8%83%E6%97%A5/</url> - <content><![CDATA[<p>钟摆晃荡 走出时间,<br>面包屑洒了一地 变成星空,<br>玻璃杯留下的牛奶唇印、折射出极光,<br>狂犬症发病具有潜伏期,<br>宇宙说它也会倦怠、凋落,</p> + <content><![CDATA[<p>钟摆晃荡 走出时间,<br> +面包屑洒了一地 变成星空,<br> +玻璃杯留下的牛奶唇印、折射出极光,<br> +狂犬症发病具有潜伏期,<br> +宇宙说它也会倦怠、凋落,</p> <p>身后伟岸的森林倒下了,我最大的遗失是没有了后悔的权利,我的忽视酿成了天地两别再无可相见的结局。</p> <p>我的眼睛面积一定小于湖,我也很少哭,你若坐在我面前,就像站在湖边,细细的雾水就扯着地连着天。</p> <blockquote> @@ -3589,9 +3923,14 @@ await prisma.$transaction(async tx => { <p>城市中独自等公车时灰白的空气,手背上青紫的针眼,嘈杂人群中的巴宝莉香水味,和长椅上听着音乐的人,都不是我。</p> <p>我是从土里长出来的,是从一方山林中长出来的。</p> <p>我在长大后成为了那一方小世界的神明,只要进了那片山林,就知道太阳从哪个方向升起,就知道每一阵风的走向,就知道从眼前经过的每一个生命从何而来。</p> -<p>我没有家,但是太阳升起的时候牵着老狗站在家人的坟包前,身后土地上的影子就是我的全家福。<br><br>在无声的融雪中泪流满面的大地,在白驹过隙的生命中,我瞥见了永恒。</p> -<p>但我无法描述它,不能说,也不能想,却又不能忘。<br>它不能变成语言,它也无法变成语言,一旦变成语言就不再是它了。<br>它是一片朦胧的温馨与寂寥,是一片成熟的希望与绝望,它的领地只有心和我身后的坟包。</p> -<p>北风似万鬼过境,<br>吹扤岭尾田堘。</p> +<p>我没有家,但是太阳升起的时候牵着老狗站在家人的坟包前,身后土地上的影子就是我的全家福。<br> +<br> +在无声的融雪中泪流满面的大地,在白驹过隙的生命中,我瞥见了永恒。</p> +<p>但我无法描述它,不能说,也不能想,却又不能忘。<br> +它不能变成语言,它也无法变成语言,一旦变成语言就不再是它了。<br> +它是一片朦胧的温馨与寂寥,是一片成熟的希望与绝望,它的领地只有心和我身后的坟包。</p> +<p>北风似万鬼过境,<br> +吹扤岭尾田堘。</p> ]]></content> <categories> <category>gallery</category> @@ -3600,7 +3939,11 @@ await prisma.$transaction(async tx => { <entry> <title>二〇二四年四月八日</title> <url>/2024/04/08/%E4%BA%8C%E3%80%87%E4%BA%8C%E5%9B%9B%E5%B9%B4%E5%9B%9B%E6%9C%88%E5%85%AB%E6%97%A5/</url> - <content><![CDATA[<p>我不预设和任何人事物共度一生,<br>就自然的生活,<br>命运把我带到哪里就到哪里,<br>有缘的话,我会在世界中看见你,<br>无缘的话,我会看见你在世界中。</p> + <content><![CDATA[<p>我不预设和任何人事物共度一生,<br> +就自然的生活,<br> +命运把我带到哪里就到哪里,<br> +有缘的话,我会在世界中看见你,<br> +无缘的话,我会看见你在世界中。</p> <p>我为人们的开心而开心,诚恳,真诚的请求看到这里的人们每天都要笑一笑哦,你们真的真的对我很重要。</p> ]]></content> <categories> @@ -3674,7 +4017,8 @@ await prisma.$transaction(async tx => { <title>二零二三年九月十三日</title> <url>/2023/09/13/%E4%BA%8C%E9%9B%B6%E4%BA%8C%E4%B8%89%E5%B9%B4%E4%B9%9D%E6%9C%88%E5%8D%81%E4%B8%89%E6%97%A5/</url> <content><![CDATA[<p>“站好! 要拍了啊,倒数三秒,都不要眨眼。” 婚礼结束后, 门口路过的陌生男人拿着相机,充当起了临时的摄影师。</p> -<p>镜头里,她和抱着雪狮的希文站在中间,她手边是依次排开的五个哥哥,希文手边是暮秋, 培元, 世琪, 婧灵五人。<br>在他们后排,其他人也各自找好位置挺直脊背站着。</p> +<p>镜头里,她和抱着雪狮的希文站在中间,她手边是依次排开的五个哥哥,希文手边是暮秋, 培元, 世琪, 婧灵五人。<br> +在他们后排,其他人也各自找好位置挺直脊背站着。</p> <p>“拍了啊,倒数,三、二、一……茄子!”</p> <p>咔擦,画面定格,幸福定格,大家终于从苦难里彻底毕业了。</p> <p>萤火虫的微光与星空交相辉映,黑夜中潜滋暗长的花香沁人心脾,晚风挠过波光粼粼的海面,彼此相爱的人相拥而眠。</p> @@ -3734,7 +4078,9 @@ await prisma.$transaction(async tx => { <entry> <title>二零二三年二月二日</title> <url>/2023/02/02/%E4%BA%8C%E9%9B%B6%E4%BA%8C%E4%B8%89%E5%B9%B4%E4%BA%8C%E6%9C%88%E4%BA%8C%E6%97%A5/</url> - <content><![CDATA[<p>我不知道这些黑乎乎的东西从哪来的,它们填满了这黄铜色的硬币每一处,像机油,像泥泞,它们随着这五角钱硬币一起从我手上换走了一袋糖果,那是一个蓬头垢面,满身泥灰的小孩,他起身看着这个给他糖果的叔叔,我蹲下看着我拥有糖果的童年。<br><br>这事很恐怖,意味着我在这个地方又多了一丝牵挂,多了一个不离开的理由。</p> + <content><![CDATA[<p>我不知道这些黑乎乎的东西从哪来的,它们填满了这黄铜色的硬币每一处,像机油,像泥泞,它们随着这五角钱硬币一起从我手上换走了一袋糖果,那是一个蓬头垢面,满身泥灰的小孩,他起身看着这个给他糖果的叔叔,我蹲下看着我拥有糖果的童年。<br> +<br> +这事很恐怖,意味着我在这个地方又多了一丝牵挂,多了一个不离开的理由。</p> ]]></content> <categories> <category>gallery</category> @@ -3761,9 +4107,11 @@ await prisma.$transaction(async tx => { <entry> <title>二零二三年八月二十七日</title> <url>/2023/08/27/%E4%BA%8C%E9%9B%B6%E4%BA%8C%E4%B8%89%E5%B9%B4%E5%85%AB%E6%9C%88%E4%BA%8C%E5%8D%81%E4%B8%83%E6%97%A5/</url> - <content><![CDATA[<p>我从失去家人的那一刻就坠入了一个朦胧而美丽的梦,梦境没有主人,我是被梦境所留下的,永远不愿醒来的旅人。<br>我足不出户,一直缩在一方小世界里面,我用了无数的理由和所有人说我的生活态度,其实勇敢的人根本不需要理由就能走出去,只有懦弱的人会用各种理由说服自己退缩</p> + <content><![CDATA[<p>我从失去家人的那一刻就坠入了一个朦胧而美丽的梦,梦境没有主人,我是被梦境所留下的,永远不愿醒来的旅人。<br> +我足不出户,一直缩在一方小世界里面,我用了无数的理由和所有人说我的生活态度,其实勇敢的人根本不需要理由就能走出去,只有懦弱的人会用各种理由说服自己退缩</p> <p>请以我为戒,大胆往前走,走到灯火通明。</p> -<p>何须纵酒方能舞翩迁,<br>赤诚相见时便是少年。</p> +<p>何须纵酒方能舞翩迁,<br> +赤诚相见时便是少年。</p> ]]></content> <categories> <category>gallery</category> @@ -3798,16 +4146,16 @@ await prisma.$transaction(async tx => { <entry> <title>二零二三年四月二十二日</title> <url>/2023/04/22/%E4%BA%8C%E9%9B%B6%E4%BA%8C%E4%B8%89%E5%B9%B4%E5%9B%9B%E6%9C%88%E4%BA%8C%E5%8D%81%E4%BA%8C%E6%97%A5/</url> - <content><![CDATA[<p> 二零二三年四月二十二日, 风沙把阳光的气息卷入帐篷, 现在是凌晨四点二十七,快天亮了, 仍有些微凉, 我即将踏入看不到边的大漠。</p> -<p> 我的心思很简单, 忘了些什么, 记起来些什么, 痛苦的根源在哪里, </p> -<p> 从这渲扰的世界沉静下来,好让我这满是凡尘虚伪的灵魂有一丝陈酿,还有世界的上方流泪的天空,和被二氧化碳覆盖的皮囊,该怎么回到最初的样子。</p> -<p> 我也曾独自冒着冷风,去薄霜铺地的林子里,为听鸟语,为盼朝阳,为寻泥土里渐次苏醒的花草,但春信不至。我是如此单独而完整,在无数个夜晚,独自顶着冷风 伫立在老橘树下的桥头,只为听一曲夜莺的哀歌,倚暖了石栏上的青苔,青苔凉透了我的心坎,但夜莺不来,夜莺不来啊。</p> -<p> 不多矫情, 秋风骀荡兮,我心向伊,漫漫黄沙兮,修我足迹!</p> -<p> 不知道这漫无边际的黄沙下面埋葬了多少文明, 只觉神秘, 但未曾有过恐惧, 我敬畏着这个世界。</p> -<p> 给岁月以文明,进入大漠只有往前,没有后路。</p> -<p> 岁月中的某个文明中的某个人,曾经也骑着骆驼向远方,又是哪个人,吟着佛门心语站在我身旁,我听见大漠的念经声。</p> -<p> 我不是个有耐心的人, 抄经书对我来说是种折磨, 我只能选择把经文抄在大地上, 黄沙上, 用自己的双腿一点点写, 用耳去倾听狂风卷积的声音。</p> -<p> 我生来就是为了把这个世界的消息和秘密带到下一个世界去。</p> + <content><![CDATA[<p>二零二三年四月二十二日, 风沙把阳光的气息卷入帐篷, 现在是凌晨四点二十七,快天亮了, 仍有些微凉, 我即将踏入看不到边的大漠。</p> +<p>我的心思很简单, 忘了些什么, 记起来些什么, 痛苦的根源在哪里,</p> +<p>从这渲扰的世界沉静下来,好让我这满是凡尘虚伪的灵魂有一丝陈酿,还有世界的上方流泪的天空,和被二氧化碳覆盖的皮囊,该怎么回到最初的样子。</p> +<p>我也曾独自冒着冷风,去薄霜铺地的林子里,为听鸟语,为盼朝阳,为寻泥土里渐次苏醒的花草,但春信不至。我是如此单独而完整,在无数个夜晚,独自顶着冷风 伫立在老橘树下的桥头,只为听一曲夜莺的哀歌,倚暖了石栏上的青苔,青苔凉透了我的心坎,但夜莺不来,夜莺不来啊。</p> +<p>不多矫情, 秋风骀荡兮,我心向伊,漫漫黄沙兮,修我足迹!</p> +<p>不知道这漫无边际的黄沙下面埋葬了多少文明, 只觉神秘, 但未曾有过恐惧, 我敬畏着这个世界。</p> +<p>给岁月以文明,进入大漠只有往前,没有后路。</p> +<p>岁月中的某个文明中的某个人,曾经也骑着骆驼向远方,又是哪个人,吟着佛门心语站在我身旁,我听见大漠的念经声。</p> +<p>我不是个有耐心的人, 抄经书对我来说是种折磨, 我只能选择把经文抄在大地上, 黄沙上, 用自己的双腿一点点写, 用耳去倾听狂风卷积的声音。</p> +<p>我生来就是为了把这个世界的消息和秘密带到下一个世界去。</p> ]]></content> <categories> <category>gallery</category> @@ -3817,14 +4165,14 @@ await prisma.$transaction(async tx => { <title>二零二三年四月二十五日</title> <url>/2023/04/25/%E4%BA%8C%E9%9B%B6%E4%BA%8C%E4%B8%89%E5%B9%B4%E5%9B%9B%E6%9C%88%E4%BA%8C%E5%8D%81%E4%BA%94%E6%97%A5/</url> <content><![CDATA[<p>一位真正的作家永远只为自己的内心写作,只有内心才会真实的告诉他,他的自私,他的高尚是多么的突出。内心让他真实地了解自己,一旦了解了自己也就了解了世界。</p> -<p> 作家要表达与之朝夕相处的现实,他常常会感到难以承受,蜂拥而来的真实几乎都在诉说着阴险丑恶和黑暗,真正的作家所追寻的是真理,这是一种排斥道德判断的真理,不是发泄,不是控诉或揭露,而是向人们展示高尚,高尚不是单纯的美好,而是对一切事物理解之后的超然,对善和恶一视同仁,用同情的目光看世界。</p> -<p> 活着的力量不是来自于喊叫,也不是来自于进攻,而是忍受,去忍受生命赋予我们的责任,去忍受现实给予我们的幸福和苦难、无聊和平庸。</p> -<p> 人是为了活着本身而活着,而不是为了活着之外的任何事物而活着。</p> -<p> 人的体验和欲望还有想象和理解,会填补所有不同的界限,会让一个人从他人的经历之中感受到自己的命运,就像是在不同的镜子里看到的都是自己的形象。</p> -<p> 我们都是这个世界上的迷路者,我们都是按照自己认定的道路寻找方向,也许我们是对的,也许我们是错的,或者有时候对了有时候错了,在出生之前和死去之前,我们谁也不知道前面的时间里在等待我们的是什么。</p> -<p> 生活是属于每个人自己的感受,不属于任何别人的看法。</p> -<p> 人们时常流出浑浊的眼泪,并不是因为人们时常悲伤,人们在高兴时甚至是在什么事都没有的平静时刻,也会有泪流出,然后举起被社会,岁月刮伤的手指,擦去眼泪,如同掸去身上的稻草。</p> -<p> 也许是困苦的生活损坏了人们的记忆,面对往事人们时常显得木讷,常常以不知所措的微笑搪塞过去,对自己的经历缺乏热情,仿佛是道听途说般只记得零星几点,即便是这零星几点也都是自身之外的记忆,用一两句话表达了一切。</p> +<p>作家要表达与之朝夕相处的现实,他常常会感到难以承受,蜂拥而来的真实几乎都在诉说着阴险丑恶和黑暗,真正的作家所追寻的是真理,这是一种排斥道德判断的真理,不是发泄,不是控诉或揭露,而是向人们展示高尚,高尚不是单纯的美好,而是对一切事物理解之后的超然,对善和恶一视同仁,用同情的目光看世界。</p> +<p>活着的力量不是来自于喊叫,也不是来自于进攻,而是忍受,去忍受生命赋予我们的责任,去忍受现实给予我们的幸福和苦难、无聊和平庸。</p> +<p>人是为了活着本身而活着,而不是为了活着之外的任何事物而活着。</p> +<p>人的体验和欲望还有想象和理解,会填补所有不同的界限,会让一个人从他人的经历之中感受到自己的命运,就像是在不同的镜子里看到的都是自己的形象。</p> +<p>我们都是这个世界上的迷路者,我们都是按照自己认定的道路寻找方向,也许我们是对的,也许我们是错的,或者有时候对了有时候错了,在出生之前和死去之前,我们谁也不知道前面的时间里在等待我们的是什么。</p> +<p>生活是属于每个人自己的感受,不属于任何别人的看法。</p> +<p>人们时常流出浑浊的眼泪,并不是因为人们时常悲伤,人们在高兴时甚至是在什么事都没有的平静时刻,也会有泪流出,然后举起被社会,岁月刮伤的手指,擦去眼泪,如同掸去身上的稻草。</p> +<p>也许是困苦的生活损坏了人们的记忆,面对往事人们时常显得木讷,常常以不知所措的微笑搪塞过去,对自己的经历缺乏热情,仿佛是道听途说般只记得零星几点,即便是这零星几点也都是自身之外的记忆,用一两句话表达了一切。</p> ]]></content> <categories> <category>gallery</category> @@ -3925,7 +4273,25 @@ await prisma.$transaction(async tx => { <url>/2025/02/11/%E4%BB%8E%E4%BA%8B%E4%BB%B6%E9%A3%8E%E6%9A%B4%E7%9C%8B%E9%A2%86%E5%9F%9F%E9%A9%B1%E5%8A%A8%E8%AE%BE%E8%AE%A1/</url> <content><![CDATA[<p>事件风暴(Event Storming)是一种领域驱动设计(DDD)的实践方法,由 Alberto Brandolini 提出,旨在通过团队协作的方式快速理解和建模业务领域。</p> <p>以下是事件风暴及相关领域驱动设计中的一些核心概念和知识点:</p> -<p>1. 领域(Domain):指的是业务相关知识的集合,可以进一步划分为子域。<br>2. 子域(Subdomain):是领域的一部分,可以是核心域、支撑域或通用域。<br>3. 核心域(Core Domain):指领域中最核心的部分,通常对应企业的核心业务。<br>4. 通用语言(Ubiquitous Language):团队所有成员使用的一种语言,用于确保业务和软件之间的沟通一致性。<br>5. 限界上下文(Bounded Context):定义了一组规则和协议,用于明确领域模型的适用范围。<br>6. 实体(Entity):具有唯一标识和生命周期的领域对象。<br>7. 值对象(Value Object):描述了某种特性或属性的对象,没有概念标识。<br>8. 聚合(Aggregate):一组相关对象的集合,由一个聚合根(Aggregate Root)统一管理。<br>9. 领域事件(Domain Event):领域中发生的重要事件,可以用于通知其他领域对象或跨限界上下文进行解耦和协作。<br>10. 命令(Command):表示要执行的操作,通常与事件一一对应。<br>11. 读模型(Read Model):为了优化读取操作而设计的模型,可能与写模型不同。<br>12. 决策命令(Decision Command):在事件风暴中,直接导致事件发生的命令。<br>13. 战略设计(Strategic Design):高层次的抽象和归类,包括理清上下文和子域的划分。<br>14. 战术设计(Tactical Design):对特定上下文下的模型进行详细设计,包括聚合、实体和值对象。<br>15. 贫血模型(Anemic Domain Model):领域对象只有属性及其getter/setter方法的纯数据类,业务逻辑通过服务实现。<br>16. 充血模型(Rich Domain Model):领域对象包含业务逻辑,每个对象都是活跃的。<br>17. 资源库(Repository):用于检索和持久化领域对象的机制。<br>18. 服务(Service):在模型中独立的操作,可以是领域服务或应用服务。<br>19. 固定规则(Invariant):为设计元素做出的断言,必须一直保持为真。</p> +<p>1. 领域(Domain):指的是业务相关知识的集合,可以进一步划分为子域。<br> +2. 子域(Subdomain):是领域的一部分,可以是核心域、支撑域或通用域。<br> +3. 核心域(Core Domain):指领域中最核心的部分,通常对应企业的核心业务。<br> +4. 通用语言(Ubiquitous Language):团队所有成员使用的一种语言,用于确保业务和软件之间的沟通一致性。<br> +5. 限界上下文(Bounded Context):定义了一组规则和协议,用于明确领域模型的适用范围。<br> +6. 实体(Entity):具有唯一标识和生命周期的领域对象。<br> +7. 值对象(Value Object):描述了某种特性或属性的对象,没有概念标识。<br> +8. 聚合(Aggregate):一组相关对象的集合,由一个聚合根(Aggregate Root)统一管理。<br> +9. 领域事件(Domain Event):领域中发生的重要事件,可以用于通知其他领域对象或跨限界上下文进行解耦和协作。<br> +10. 命令(Command):表示要执行的操作,通常与事件一一对应。<br> +11. 读模型(Read Model):为了优化读取操作而设计的模型,可能与写模型不同。<br> +12. 决策命令(Decision Command):在事件风暴中,直接导致事件发生的命令。<br> +13. 战略设计(Strategic Design):高层次的抽象和归类,包括理清上下文和子域的划分。<br> +14. 战术设计(Tactical Design):对特定上下文下的模型进行详细设计,包括聚合、实体和值对象。<br> +15. 贫血模型(Anemic Domain Model):领域对象只有属性及其getter/setter方法的纯数据类,业务逻辑通过服务实现。<br> +16. 充血模型(Rich Domain Model):领域对象包含业务逻辑,每个对象都是活跃的。<br> +17. 资源库(Repository):用于检索和持久化领域对象的机制。<br> +18. 服务(Service):在模型中独立的操作,可以是领域服务或应用服务。<br> +19. 固定规则(Invariant):为设计元素做出的断言,必须一直保持为真。</p> <p>事件风暴通常包括以下步骤:</p> <ul> <li>识别领域事件</li> @@ -3944,7 +4310,9 @@ await prisma.$transaction(async tx => { <entry> <title>儿童新型冠状病毒Omicron株和肺炎支原体混合感染重症肺炎1例</title> <url>/2023/10/25/%E5%84%BF%E7%AB%A5%E6%96%B0%E5%9E%8B%E5%86%A0%E7%8A%B6%E7%97%85%E6%AF%92Omicron%E6%A0%AA%E5%92%8C%E8%82%BA%E7%82%8E%E6%94%AF%E5%8E%9F%E4%BD%93%E6%B7%B7%E5%90%88%E6%84%9F%E6%9F%93%E9%87%8D%E7%97%87%E8%82%BA%E7%82%8E1%E4%BE%8B/</url> - <content><![CDATA[<p>患儿 男, 3 岁 10 月龄,因“间歇发热 2 周伴咳嗽、气促”入上海交通大学医学院附属仁济医院(南部院区)定点医院隔离病房。<br>患儿病初发热,确诊为新型冠状病毒肺炎(简称新冠肺炎),热退 2d 再次持续高热>3d 伴气促、吸气性凹陷,胸部 CT 示右肺下叶片状密度影,诊断“重型新冠肺炎”,行支气管镜肺泡灌洗,宏基因组病原检测确诊为混合肺炎支原体感染,治疗好转出院。<br>提示临床医生诊治重型新冠肺炎时需警惕混合感染</p> + <content><![CDATA[<p>患儿 男, 3 岁 10 月龄,因“间歇发热 2 周伴咳嗽、气促”入上海交通大学医学院附属仁济医院(南部院区)定点医院隔离病房。<br> +患儿病初发热,确诊为新型冠状病毒肺炎(简称新冠肺炎),热退 2d 再次持续高热>3d 伴气促、吸气性凹陷,胸部 CT 示右肺下叶片状密度影,诊断“重型新冠肺炎”,行支气管镜肺泡灌洗,宏基因组病原检测确诊为混合肺炎支原体感染,治疗好转出院。<br> +提示临床医生诊治重型新冠肺炎时需警惕混合感染</p> <ul> <li><a href="../papers/%E5%84%BF%E7%AB%A5%E6%96%B0%E5%9E%8B%E5%86%A0%E7%8A%B6%E7%97%85%E6%AF%92Omicron%E6%A0%AA%E5%92%8C%E8%82%BA%E7%82%8E%E6%94%AF%E5%8E%9F%E4%BD%93%E6%B7%B7%E5%90%88%E6%84%9F%E6%9F%93%E9%87%8D%E7%97%87%E8%82%BA%E7%82%8E1%E4%BE%8B.pdf">报告原档</a></li> </ul> @@ -3959,10 +4327,13 @@ await prisma.$transaction(async tx => { <content><![CDATA[<p>这里给出一些在冬季,临床上简单诊断咳嗽的例子,仅供参考, 无论结果如何, 立刻就医.</p> <p>这里简单分成有痰和无痰(或痰少)两类, 然后分别以时间段细分:</p> <ul> -<li>有痰<ul> -<li>夜间咳:<ul> +<li>有痰 +<ul> +<li>夜间咳: +<ul> <li>刚睡着就咳嗽,坐起来会好点: 可能是鼻涕倒流刺激咽喉, 也可能是上呼吸道感染, 比如过敏性或非过敏性鼻炎, 急慢性鼻窦炎</li> -<li>凌晨四五点咳醒:<ul> +<li>凌晨四五点咳醒: +<ul> <li>长期如此: 考虑哮喘发作</li> <li>短期如此: 考虑支气管炎</li> </ul> @@ -3970,29 +4341,35 @@ await prisma.$transaction(async tx => { <li>睡到一半胸闷气短, 咳嗽甚至咳出带血丝的痰: 考虑心脏病</li> </ul> </li> -<li>每天不定时咳嗽: 这种情况在临床上一般是烟抽多了, 也有可能是慢性肺阻塞, 慢性支气管炎, 支气管扩张, 肺气肿引起的<ul> +<li>每天不定时咳嗽: 这种情况在临床上一般是烟抽多了, 也有可能是慢性肺阻塞, 慢性支气管炎, 支气管扩张, 肺气肿引起的 +<ul> <li>带血,呼吸困难,体重下降:考虑肺结核或肺癌</li> </ul> </li> -<li>无特定时间咳嗽:<ul> +<li>无特定时间咳嗽: +<ul> <li>伴有鼻子难受, 浑身乏力等: 考虑过敏, 环境过敏,(比如像新装修的屋子里的甲醛)或者药物过敏(比如降压药)</li> </ul> </li> </ul> </li> -<li>无痰(或痰少)<ul> +<li>无痰(或痰少) +<ul> <li>白天咳: 常见于急慢性咽喉炎(一开口说话就想咳嗽, 不说话或睡大觉的时候不想咳)</li> -<li>夜间咳<ul> +<li>夜间咳 +<ul> <li>睡着睡着突然猛咳, 还有胸闷胀气, 口干口苦, 声音嘶哑, 心灼热之类的症状: 一般是胃食管反流导致的</li> <li>睡眠中咳嗽不止,像被呛到一样, 睡得浅梦还多: 考虑上呼吸道阻塞症候群, 可能与睡眠暂停呼吸症有关</li> </ul> </li> -<li>每天不定时咳嗽:<ul> +<li>每天不定时咳嗽: +<ul> <li>小孩和老人首先判断是否误吸异物</li> <li>否则可能是咽喉神经过度敏感</li> </ul> </li> -<li>无特定时间咳嗽: <ul> +<li>无特定时间咳嗽: +<ul> <li>可能由于某些心理问题, 紧张焦虑之类的</li> </ul> </li> @@ -4002,12 +4379,14 @@ await prisma.$transaction(async tx => { <hr> <p>接下来是一些参考的, 以食疗为主的方子, 注意, 不要随便吃药, 无论如何遵医嘱, 考虑自己身体情况, 过敏原.</p> <ol> -<li>咳嗽多痰可以以芦根为主, 竹茹入肺, 胃两经, 可以清肺化痰<ul> +<li>咳嗽多痰可以以芦根为主, 竹茹入肺, 胃两经, 可以清肺化痰 +<ul> <li>新鲜芦根100克,竹茹15克,芦根切碎和竹茹一起放水里煎一会儿,然后用汁水煮粥喝</li> <li>配合甘草也可以平喘止咳,但注意,脾胃虚寒的话不可用: 芦根50克, 甘草5克, 加1L水煮沸十分钟,去掉渣渣喝100毫升, 喝多了也不太好.</li> </ul> </li> -<li>当然还有常见的冰糖雪梨啦, 经典的润肺止咳:<ul> +<li>当然还有常见的冰糖雪梨啦, 经典的润肺止咳: +<ul> <li>买个漂亮的大梨, 顶上削一块, 挖空里面, 把挖出来的果肉切块重新放进去, 再加入川贝母粉, 冰糖, 陈皮, 大火煮沸之后立刻转小火蒸三刻钟</li> </ul> </li> @@ -4023,27 +4402,39 @@ await prisma.$transaction(async tx => { <title>发热及超高热危象</title> <url>/2023/06/17/%E5%8F%91%E7%83%AD%E5%8F%8A%E8%B6%85%E9%AB%98%E7%83%AD%E5%8D%B1%E8%B1%A1/</url> <content><![CDATA[<p>应急诊断与处理放在开头,理论放在后面</p> -<h2 id="处理"><a href="#处理" class="headerlink" title="处理"></a>处理</h2><h3 id="支持治疗"><a href="#支持治疗" class="headerlink" title="支持治疗"></a>支持治疗</h3><p>患者出现神志改变、呼吸窘迫、血流动力学不稳定等危及生命的症状与体征时,立即实施监护、建立静脉通路、气道管理、补液以及氧疗,必要时予以呼吸支持治疗。</p> -<h3 id="超高热危象的处理"><a href="#超高热危象的处理" class="headerlink" title="超高热危象的处理"></a>超高热危象的处理</h3><p>一旦出现超高热,应以最快的速度降低中心体温、代谢率,以打断超高热引起的恶性循环,同时防治各种并发症。其中,降温是抢救超高热危象的主要措施。降温速度决定预后,应在1小时内使直肠温度降至38.5℃以内。</p> -<h3 id="对症处理"><a href="#对症处理" class="headerlink" title="对症处理"></a>对症处理</h3><p>发热的对症治疗包括:</p> +<h2 id="处理"><a class="header-anchor" href="#处理">¶</a>处理</h2> +<h3 id="支持治疗"><a class="header-anchor" href="#支持治疗">¶</a>支持治疗</h3> +<p>患者出现神志改变、呼吸窘迫、血流动力学不稳定等危及生命的症状与体征时,立即实施监护、建立静脉通路、气道管理、补液以及氧疗,必要时予以呼吸支持治疗。</p> +<h3 id="超高热危象的处理"><a class="header-anchor" href="#超高热危象的处理">¶</a>超高热危象的处理</h3> +<p>一旦出现超高热,应以最快的速度降低中心体温、代谢率,以打断超高热引起的恶性循环,同时防治各种并发症。其中,降温是抢救超高热危象的主要措施。降温速度决定预后,应在1小时内使直肠温度降至38.5℃以内。</p> +<h3 id="对症处理"><a class="header-anchor" href="#对症处理">¶</a>对症处理</h3> +<p>发热的对症治疗包括:</p> <ol> <li>物理降温:一般可用冷毛巾湿敷额部,每5~10分钟更换1次,或用冰袋置于额、枕后、颈、腋和腹股沟处降温,或用25%~50%乙醇擦浴。或头置冰帽、冰水灌肠、冷盐水洗胃,或将患者置于空调房内(使室温维持在27℃左右)。应根据具体条件选用。</li> -<li>药物降温:视发热程度可采用口服或肌注解热镇痛药。常用的口服解热镇痛药有:阿司匹林(0.3~0.6g/次)、对乙酰氨基酚(0.3~0.5g/次)、布洛芬(0.2~0.4g/次)、安乃近(0.25~0.5g/次)、解热止痛片(APC片,1~2片/次)、速效伤风胶囊(1~2粒/次)、复方对乙酰氨基酚片(1~2片/次)等。常用的注射用解热镇痛药有:阿司匹林精氨酸盐(0.5~1.0g/次)、阿司匹林赖氨酸盐(赖氨匹林,0.9~1.8g/次)、对乙酰氨基酚(0.15~0.25g/次)、息热痛注射液(2ml/次)、复方氨林巴比妥注射液(1支/次)等。高热者病情需要时可短期应用肾上腺皮质激素,如地塞米松5~10mg静注或肌注;或以地塞米松12~20mg/d或氢化可的松300~600mg/d静滴。</li> +<li>药物降温:视发热程度可采用口服或肌注解热镇痛药。常用的口服解热镇痛药有:阿司匹林(0.3~0.6g/次)、对乙酰氨基酚(0.3~0.5g/次)、布洛芬(0.2~0.4g/次)、安乃近(0.25~0.5g/次)、解热止痛片(APC片,1~2片/次)、速效伤风胶囊(1~2粒/次)、复方对乙酰氨基酚片(1~2片/次)等。常用的注射用解热镇痛药有:阿司匹林精氨酸盐(0.5~1.0g/次)、阿司匹林赖氨酸盐(赖氨匹林,0.9~1.8g/次)、对乙酰氨基酚(0.15~0.25g/次)、息热痛注射液(2ml/次)、复方氨林巴比妥注射液(1支/次)等。高热者病情需要时可短期应用肾上腺皮质激素,如地塞米松5~10mg静注或肌注;或以地塞米松12~20mg/d或氢化可的松300~600mg/d静滴。</li> </ol> -<h3 id="抗生素经验性应用"><a href="#抗生素经验性应用" class="headerlink" title="抗生素经验性应用"></a>抗生素经验性应用</h3><p>对感染病例早期抗生素经验性应用是有益的。一般来讲,若有明确的病原菌感染,则选择覆盖特定病原菌感染的窄谱抗生素;若不明确,可选择覆盖革兰阳性和革兰阴性需氧菌、厌氧菌的广谱抗生素。</p> -<h3 id="诊断性治疗"><a href="#诊断性治疗" class="headerlink" title="诊断性治疗"></a>诊断性治疗</h3><p>当发热病因一时难以查明时,在不影响进一步检查的情况下,可按可能性较大的病因进行诊断性治疗(如疑疟疾,可试用氯喹;疑阿米巴性肝脓肿,行抗阿米巴治疗;疑结核病行抗结核治疗时间以3~4周以上为宜),期望获得疗效而做出临床诊断。诊断性治疗应选用特异性强、疗效确切及安全性大的治疗药物,剂量应充足并完成整个疗程,无特殊原因不得随便更换试验药物。</p> -<h2 id="诊断"><a href="#诊断" class="headerlink" title="诊断"></a>诊断</h2><h3 id="病史"><a href="#病史" class="headerlink" title="病史"></a>病史</h3><p>详细询问病史对发热原因的诊断常能提供重要线索。此外,对发热患者定期检测体温,密切观察热度的高低、时限、热型等也有重要价值。</p> +<h3 id="抗生素经验性应用"><a class="header-anchor" href="#抗生素经验性应用">¶</a>抗生素经验性应用</h3> +<p>对感染病例早期抗生素经验性应用是有益的。一般来讲,若有明确的病原菌感染,则选择覆盖特定病原菌感染的窄谱抗生素;若不明确,可选择覆盖革兰阳性和革兰阴性需氧菌、厌氧菌的广谱抗生素。</p> +<h3 id="诊断性治疗"><a class="header-anchor" href="#诊断性治疗">¶</a>诊断性治疗</h3> +<p>当发热病因一时难以查明时,在不影响进一步检查的情况下,可按可能性较大的病因进行诊断性治疗(如疑疟疾,可试用氯喹;疑阿米巴性肝脓肿,行抗阿米巴治疗;疑结核病行抗结核治疗时间以3~4周以上为宜),期望获得疗效而做出临床诊断。诊断性治疗应选用特异性强、疗效确切及安全性大的治疗药物,剂量应充足并完成整个疗程,无特殊原因不得随便更换试验药物。</p> +<h2 id="诊断"><a class="header-anchor" href="#诊断">¶</a>诊断</h2> +<h3 id="病史"><a class="header-anchor" href="#病史">¶</a>病史</h3> +<p>详细询问病史对发热原因的诊断常能提供重要线索。此外,对发热患者定期检测体温,密切观察热度的高低、时限、热型等也有重要价值。</p> <ol> -<li><p>起病方式: 一般而言,急性感染性疾病起病多较急骤,常有受凉、疲劳、外伤或进食不洁食物等病史,若发热前有明显寒战者,多属化脓性细菌感染或疟疾;而一般非感染性发热,以及结核、伤寒、立克次体和病毒感染多无寒战。</p> +<li> +<p>起病方式: 一般而言,急性感染性疾病起病多较急骤,常有受凉、疲劳、外伤或进食不洁食物等病史,若发热前有明显寒战者,多属化脓性细菌感染或疟疾;而一般非感染性发热,以及结核、伤寒、立克次体和病毒感染多无寒战。</p> </li> -<li><p>发热的分期与分型</p> +<li> +<p>发热的分期与分型</p> +<ol> +<li>体温上升期:表现为疲乏、不适感、肌肉酸痛、皮肤苍白、干燥、无汗、畏寒或寒战等症状。体温上升有两种形式: <ol> -<li>体温上升期:表现为疲乏、不适感、肌肉酸痛、皮肤苍白、干燥、无汗、畏寒或寒战等症状。体温上升有两种形式:<ol> <li>骤升型:体温在数小时内达39~40℃以上,常伴有寒战</li> <li>缓升型:体温于数日内缓慢上升达高峰。</li> </ol> </li> -<li>高热持续期:此时体温已达高峰,临床表现为皮肤潮红而灼热,呼吸加快加强,可有出汗。此期持续数小时、数天或数周。其热型(体温曲线)可表现为:<ol> +<li>高热持续期:此时体温已达高峰,临床表现为皮肤潮红而灼热,呼吸加快加强,可有出汗。此期持续数小时、数天或数周。其热型(体温曲线)可表现为: +<ol> <li>稽留热(continued fever):体温持续于39~40℃左右,达数天或数周,24小时波动范围不超过1℃。见于肺炎、伤寒、斑疹伤寒(早期)等。</li> <li>弛张热(remittent fever):体温在39℃以上,但波动幅度大,24小时内体温差达2℃以上,体温最低时一般仍高于正常水平。见于脓毒血症、风湿热、重症结核、化脓性炎症如肝脓肿等</li> <li>间歇热(intermittent fever):高热期与无热期交替地出现。体温波动幅度可达数度。无热期(间歇期)持续1天乃至数天,反复发作。见于疟疾、急性肾盂肾炎、局限性化脓性感染等。</li> @@ -4051,9 +4442,9 @@ await prisma.$transaction(async tx => { <li>波状热(undulant fever):体温逐渐升高达39℃或以上,数天后又逐渐下降至正常水平,数天后又逐渐升高,如此反复多次,常见于布鲁菌病、恶性淋巴瘤等。</li> <li>不规则热(irregular fever):发热持续时间不定,变动无规律,可见于肺结核、感染性心内膜炎等。</li> </ol> -<p> </p> </li> -<li>体温下降期: 由于机体的防御功能与适当的治疗,疾病得到控制,体温恢复正常。体温下降的方式有两种:<ol> +<li>体温下降期: 由于机体的防御功能与适当的治疗,疾病得到控制,体温恢复正常。体温下降的方式有两种: +<ol> <li>骤降(crisis):体温于数小时内迅速降至正常,有时可低于正常,常伴有大汗。常见于疟疾、急性肾盂肾炎、肺炎及输液反应等。</li> <li>渐降(lysis):体温于数天内逐渐降至正常。如伤寒、风湿热等</li> </ol> @@ -4061,45 +4452,63 @@ await prisma.$transaction(async tx => { </ol> </li> </ol> -<h4 id="伴随症状"><a href="#伴随症状" class="headerlink" title="伴随症状"></a>伴随症状</h4><p>重视具有定位意义的伴发的局部症状,以便确定主要病变在哪个系统。如发热伴有鼻塞流涕、咽痛、咳嗽,而一般情况良好者多为上呼吸道感染,若有胸痛、咯铁锈色痰和呼吸困难者,则多为下呼吸道感染,如肺炎。发热伴神经系统症状,如头痛、呕吐、昏迷、惊厥、脑膜刺激征等则表示病变在中枢神经系统,应考虑各种脑膜炎、脑炎、中暑、急性脑卒中等;但儿童易有高热惊厥,不一定有严重脑部病变。发热伴有肋椎角、腰肋部疼痛及尿频、脓尿、血尿者提示多为泌尿系统感染。发热伴有明显关节痛或关节炎症状者应多考虑风湿热等结缔组织疾病。发热伴有恶心呕吐、腹痛、腹泻者,应多考虑急性胃肠道炎症。发热、黄疸伴右上腹痛应注意肝胆感染。依此类推。</p> -<h3 id="流行病学"><a href="#流行病学" class="headerlink" title="流行病学"></a>流行病学</h3><p>如患者来自的地区、年龄、性别、职业、发病季节、旅游史、接触感染史等,尤其是传染病的流行病学史非常重要。如布鲁菌病多见于从事畜牧业(尤其是动物接生)的人群中;同性恋者及静注毒品成瘾者的发热待查以艾滋病或合并机会性感染的可能性较大</p> -<h3 id="体态"><a href="#体态" class="headerlink" title="体态"></a>体态</h3><p>遇急重发热患者,应首先测呼吸、脉搏、血压等重要生命体征,并快速进行全面的体格检查,重点检查皮肤、黏膜有无皮疹、淤点以及肝、脾、淋巴结肿大等。发热伴有中毒性休克时,患者面色青灰,脉细速,血压下降或测不出,见于休克型肺炎、暴发性流行性脑脊髓膜炎、中毒性菌痢、脓毒症、流行性出血热等。</p> -<h4 id="面容"><a href="#面容" class="headerlink" title="面容"></a>面容</h4><p>一般急性感染多呈急热面容。伤寒、副伤寒者常表情淡漠,即所谓“伤寒面容”。斑疹伤寒、恙虫病、流行性出血热患者常呈醉酒样面容。猩红热患者见口周苍白。麻疹患者常见眼睑水肿、结膜充血、分泌物增多等。急性白血病、再生障碍性贫血和恶性组织细胞病常因贫血亦可呈面色苍白。发热伴面部蝶形红斑是播散性红斑狼疮的特殊病症。口唇疱疹可见于大叶性肺炎、间日疟、流行性脑脊髓膜炎、流行性感冒、大肠杆菌败血症等。</p> -<h4 id="皮肤特征"><a href="#皮肤特征" class="headerlink" title="皮肤特征"></a>皮肤特征</h4><p>注意有无皮疹及出血点。皮肤多汗可见于结核病、风湿热、败血症、恶性淋巴瘤。皮肤发疹可见于猩红热、麻疹、风疹、斑疹伤寒、伤寒、水痘、恙虫病、传染性单核细胞增多症、丹毒、红斑狼疮、急性皮肌炎等,根据其特征性皮疹及出疹日期可对急性发疹性传染病作出诊断:</p> +<h4 id="伴随症状"><a class="header-anchor" href="#伴随症状">¶</a>伴随症状</h4> +<p>重视具有定位意义的伴发的局部症状,以便确定主要病变在哪个系统。如发热伴有鼻塞流涕、咽痛、咳嗽,而一般情况良好者多为上呼吸道感染,若有胸痛、咯铁锈色痰和呼吸困难者,则多为下呼吸道感染,如肺炎。发热伴神经系统症状,如头痛、呕吐、昏迷、惊厥、脑膜刺激征等则表示病变在中枢神经系统,应考虑各种脑膜炎、脑炎、中暑、急性脑卒中等;但儿童易有高热惊厥,不一定有严重脑部病变。发热伴有肋椎角、腰肋部疼痛及尿频、脓尿、血尿者提示多为泌尿系统感染。发热伴有明显关节痛或关节炎症状者应多考虑风湿热等结缔组织疾病。发热伴有恶心呕吐、腹痛、腹泻者,应多考虑急性胃肠道炎症。发热、黄疸伴右上腹痛应注意肝胆感染。依此类推。</p> +<h3 id="流行病学"><a class="header-anchor" href="#流行病学">¶</a>流行病学</h3> +<p>如患者来自的地区、年龄、性别、职业、发病季节、旅游史、接触感染史等,尤其是传染病的流行病学史非常重要。如布鲁菌病多见于从事畜牧业(尤其是动物接生)的人群中;同性恋者及静注毒品成瘾者的发热待查以艾滋病或合并机会性感染的可能性较大</p> +<h3 id="体态"><a class="header-anchor" href="#体态">¶</a>体态</h3> +<p>遇急重发热患者,应首先测呼吸、脉搏、血压等重要生命体征,并快速进行全面的体格检查,重点检查皮肤、黏膜有无皮疹、淤点以及肝、脾、淋巴结肿大等。发热伴有中毒性休克时,患者面色青灰,脉细速,血压下降或测不出,见于休克型肺炎、暴发性流行性脑脊髓膜炎、中毒性菌痢、脓毒症、流行性出血热等。</p> +<h4 id="面容"><a class="header-anchor" href="#面容">¶</a>面容</h4> +<p>一般急性感染多呈急热面容。伤寒、副伤寒者常表情淡漠,即所谓“伤寒面容”。斑疹伤寒、恙虫病、流行性出血热患者常呈醉酒样面容。猩红热患者见口周苍白。麻疹患者常见眼睑水肿、结膜充血、分泌物增多等。急性白血病、再生障碍性贫血和恶性组织细胞病常因贫血亦可呈面色苍白。发热伴面部蝶形红斑是播散性红斑狼疮的特殊病症。口唇疱疹可见于大叶性肺炎、间日疟、流行性脑脊髓膜炎、流行性感冒、大肠杆菌败血症等。</p> +<h4 id="皮肤特征"><a class="header-anchor" href="#皮肤特征">¶</a>皮肤特征</h4> +<p>注意有无皮疹及出血点。皮肤多汗可见于结核病、风湿热、败血症、恶性淋巴瘤。皮肤发疹可见于猩红热、麻疹、风疹、斑疹伤寒、伤寒、水痘、恙虫病、传染性单核细胞增多症、丹毒、红斑狼疮、急性皮肌炎等,根据其特征性皮疹及出疹日期可对急性发疹性传染病作出诊断:</p> <p><img src="/img/%E5%8C%BB%E5%AD%A6/%E6%A0%B9%E6%8D%AE%E7%89%B9%E5%BE%81%E6%80%A7%E7%9A%AE%E7%96%B9%E5%8F%8A%E5%87%BA%E7%96%B9%E6%97%A5%E6%9C%9F%E5%AF%B9%E6%80%A5%E6%80%A7%E5%8F%91%E7%96%B9%E6%80%A7%E4%BC%A0%E6%9F%93%E7%97%85%E4%BD%9C%E5%87%BA%E8%AF%8A%E6%96%AD.png" alt="根据特征性皮疹及出疹日期对急性发疹性传染病作出诊断.png"></p> <p>注意有无皮疹及出血点。皮肤多汗可见于结核病、风湿热、败血症、恶性淋巴瘤。皮肤发疹可见于猩红热、麻疹、风疹、斑疹伤寒、伤寒、水痘、恙虫病、传染性单核细胞增多症、丹毒、红斑狼疮、急性皮肌炎等,根据其特征性皮疹及出疹日期可对急性发疹性传染病作出诊断。</p> -<h4 id="淋巴结肿大"><a href="#淋巴结肿大" class="headerlink" title="淋巴结肿大"></a>淋巴结肿大</h4><p>注意有无皮疹及出血点。皮肤多汗可见于结核病、风湿热、败血症、恶性淋巴瘤。皮肤发疹可见于猩红热、麻疹、风疹、斑疹伤寒、伤寒、水痘、恙虫病、传染性单核细胞增多症、丹毒、红斑狼疮、急性皮肌炎等,根据其特征性皮疹及出疹日期可对急性发疹性传染病作出诊断</p> -<h4 id="脾大"><a href="#脾大" class="headerlink" title="脾大"></a>脾大</h4><p>注意有无皮疹及出血点。皮肤多汗可见于结核病、风湿热、败血症、恶性淋巴瘤。皮肤发疹可见于猩红热、麻疹、风疹、斑疹伤寒、伤寒、水痘、恙虫病、传染性单核细胞增多症、丹毒、红斑狼疮、急性皮肌炎等,根据其特征性皮疹及出疹日期可对急性发疹性传染病作出诊断。</p> -<h4 id="胸部体征"><a href="#胸部体征" class="headerlink" title="胸部体征"></a>胸部体征</h4><p>如闻及肺部干湿性啰音或实变体征等,应考虑呼吸系统感染;发热伴有栓塞、心脏杂音,尤其是原有器质性心脏病者心脏杂音发生明显改变时,应注意感染性心内膜炎;发热伴心包摩擦音或心包积液体征,常提示心包炎。而急性心肌炎常表现为发热与心率不成比例,心率增快常超过发热程度。</p> -<h4 id="肌肉与关节"><a href="#肌肉与关节" class="headerlink" title="肌肉与关节"></a>肌肉与关节</h4><p>发热伴肌肉疼痛见于许多传染病,一般无特殊性诊断意义,但如腓肠肌剧烈疼痛,甚至不能站立或行走,常提示钩端螺旋体病。局部肌痛兼有发热与白细胞增多,须检查有无深部脓肿,尤其是药物肌内注射引起的臀肌无菌性脓肿。发热伴多关节肿痛,病因常为各种关节炎,如化脓性、感染中毒性与变态反应性等,而淋病性与结核性关节炎常侵犯单个的大关节。</p> -<h4 id="其他"><a href="#其他" class="headerlink" title="其他"></a>其他</h4><p>长期不明原因的发热患者尤应注意隐蔽性病灶,如肝脏、膈下、脊椎、盆腔、鼻窦、乳突等局部脓肿。肝脓肿是引起长期发热的常见病因,在早期不一定有局部症状。脊椎病变如结核或脓毒症后脊椎旁化脓性病灶在体检时易被忽略。男性患者的睾丸与附睾检查、女性患者的盆腔检查,以及所有发热待查患者的直肠指检或乙状结肠镜检查均应列为常规。眼底检查也应作为常规,粟粒性结核可有眼脉络膜结核结节,年老患者肛门指检可发现前列腺脓肿。此外,腹部与盆腔手术(包括引产)后发热可由腹腔或盆腔内隐蔽的脓肿引起。</p> -<h3 id="辅助检查"><a href="#辅助检查" class="headerlink" title="辅助检查"></a>辅助检查</h3><p>对发热患者行辅助检查时必须掌握检查目的明确,并以简便快捷为原则。对于通过病史询问和体检能确诊者不一定均作有关检查。常用的辅助检查包括:①血、尿、粪常规检查。②血清学检查:如肥达、外斐反应、钩端螺旋体病的凝集溶解试验,乙脑的补体结合试验,系统性红斑狼疮的抗核抗体试验等。③血或骨髓培养:对伤寒、副伤寒、脓毒症、细菌性心内膜炎等疾病的病原诊断均具有决定性意义。④X线、CT与MRI检查:CT与MRI检查对诊断骨盆内、膈下与腹腔深部隐蔽性脓肿,尤其对发现腹膜后病灶如淋巴瘤、脓肿、血肿等有重要价值。⑤超声检查:对疑有急性渗出性心包炎和感染性心内膜炎患者,可行超声心动图检查。腹部超声波检查适用于疑有腹腔内占位性病变、肝脓肿、肝胆道结石以及肾脓肿、泌尿系结石等患者。⑥活体组织检查:如肝穿刺活组织检查、淋巴结以及皮损与皮下结节活体组织检查等。骨髓检查对白血病、恶性组织细胞病等具有决定性诊断价值。</p> -<h3 id="病因诊断"><a href="#病因诊断" class="headerlink" title="病因诊断"></a>病因诊断</h3><p>发热是由于各种原因导致机体产热过多或散热减少,以及体温中枢功能障碍所致。其原因很多且复杂。在临床实践中,以发热为主诉或唯一症状就诊者有急性发热,尤其出疹性发热,原因不明发热,长期低热,超高热与反复发热。其病因特征亦各异。</p> -<h4 id="急性发热"><a href="#急性发热" class="headerlink" title="急性发热"></a>急性发热</h4><p>热程在2周以内的发热称为急性发热。其原因很多,绝大多数属于感染,尤以呼吸道、泌尿道和消化道感染最常见,因为这些系统与外界相通,最易遭受病原体的侵袭。在排除上述系统感染后,则要注意某些急性传染病和其他系统的感染。</p> -<h4 id="长期“不明原因”的中、高热"><a href="#长期“不明原因”的中、高热" class="headerlink" title="长期“不明原因”的中、高热"></a>长期“不明原因”的中、高热</h4><p>系指发热持续3周以上,体温多次超过38.3℃,经过至少1周深入细致的检查仍不能确诊的一组疾病,主要有感染、恶性肿瘤与结缔组织-血管性疾病三大类</p> +<h4 id="淋巴结肿大"><a class="header-anchor" href="#淋巴结肿大">¶</a>淋巴结肿大</h4> +<p>注意有无皮疹及出血点。皮肤多汗可见于结核病、风湿热、败血症、恶性淋巴瘤。皮肤发疹可见于猩红热、麻疹、风疹、斑疹伤寒、伤寒、水痘、恙虫病、传染性单核细胞增多症、丹毒、红斑狼疮、急性皮肌炎等,根据其特征性皮疹及出疹日期可对急性发疹性传染病作出诊断</p> +<h4 id="脾大"><a class="header-anchor" href="#脾大">¶</a>脾大</h4> +<p>注意有无皮疹及出血点。皮肤多汗可见于结核病、风湿热、败血症、恶性淋巴瘤。皮肤发疹可见于猩红热、麻疹、风疹、斑疹伤寒、伤寒、水痘、恙虫病、传染性单核细胞增多症、丹毒、红斑狼疮、急性皮肌炎等,根据其特征性皮疹及出疹日期可对急性发疹性传染病作出诊断。</p> +<h4 id="胸部体征"><a class="header-anchor" href="#胸部体征">¶</a>胸部体征</h4> +<p>如闻及肺部干湿性啰音或实变体征等,应考虑呼吸系统感染;发热伴有栓塞、心脏杂音,尤其是原有器质性心脏病者心脏杂音发生明显改变时,应注意感染性心内膜炎;发热伴心包摩擦音或心包积液体征,常提示心包炎。而急性心肌炎常表现为发热与心率不成比例,心率增快常超过发热程度。</p> +<h4 id="肌肉与关节"><a class="header-anchor" href="#肌肉与关节">¶</a>肌肉与关节</h4> +<p>发热伴肌肉疼痛见于许多传染病,一般无特殊性诊断意义,但如腓肠肌剧烈疼痛,甚至不能站立或行走,常提示钩端螺旋体病。局部肌痛兼有发热与白细胞增多,须检查有无深部脓肿,尤其是药物肌内注射引起的臀肌无菌性脓肿。发热伴多关节肿痛,病因常为各种关节炎,如化脓性、感染中毒性与变态反应性等,而淋病性与结核性关节炎常侵犯单个的大关节。</p> +<h4 id="其他"><a class="header-anchor" href="#其他">¶</a>其他</h4> +<p>长期不明原因的发热患者尤应注意隐蔽性病灶,如肝脏、膈下、脊椎、盆腔、鼻窦、乳突等局部脓肿。肝脓肿是引起长期发热的常见病因,在早期不一定有局部症状。脊椎病变如结核或脓毒症后脊椎旁化脓性病灶在体检时易被忽略。男性患者的睾丸与附睾检查、女性患者的盆腔检查,以及所有发热待查患者的直肠指检或乙状结肠镜检查均应列为常规。眼底检查也应作为常规,粟粒性结核可有眼脉络膜结核结节,年老患者肛门指检可发现前列腺脓肿。此外,腹部与盆腔手术(包括引产)后发热可由腹腔或盆腔内隐蔽的脓肿引起。</p> +<h3 id="辅助检查"><a class="header-anchor" href="#辅助检查">¶</a>辅助检查</h3> +<p>对发热患者行辅助检查时必须掌握检查目的明确,并以简便快捷为原则。对于通过病史询问和体检能确诊者不一定均作有关检查。常用的辅助检查包括:①血、尿、粪常规检查。②血清学检查:如肥达、外斐反应、钩端螺旋体病的凝集溶解试验,乙脑的补体结合试验,系统性红斑狼疮的抗核抗体试验等。③血或骨髓培养:对伤寒、副伤寒、脓毒症、细菌性心内膜炎等疾病的病原诊断均具有决定性意义。④X线、CT与MRI检查:CT与MRI检查对诊断骨盆内、膈下与腹腔深部隐蔽性脓肿,尤其对发现腹膜后病灶如淋巴瘤、脓肿、血肿等有重要价值。⑤超声检查:对疑有急性渗出性心包炎和感染性心内膜炎患者,可行超声心动图检查。腹部超声波检查适用于疑有腹腔内占位性病变、肝脓肿、肝胆道结石以及肾脓肿、泌尿系结石等患者。⑥活体组织检查:如肝穿刺活组织检查、淋巴结以及皮损与皮下结节活体组织检查等。骨髓检查对白血病、恶性组织细胞病等具有决定性诊断价值。</p> +<h3 id="病因诊断"><a class="header-anchor" href="#病因诊断">¶</a>病因诊断</h3> +<p>发热是由于各种原因导致机体产热过多或散热减少,以及体温中枢功能障碍所致。其原因很多且复杂。在临床实践中,以发热为主诉或唯一症状就诊者有急性发热,尤其出疹性发热,原因不明发热,长期低热,超高热与反复发热。其病因特征亦各异。</p> +<h4 id="急性发热"><a class="header-anchor" href="#急性发热">¶</a>急性发热</h4> +<p>热程在2周以内的发热称为急性发热。其原因很多,绝大多数属于感染,尤以呼吸道、泌尿道和消化道感染最常见,因为这些系统与外界相通,最易遭受病原体的侵袭。在排除上述系统感染后,则要注意某些急性传染病和其他系统的感染。</p> +<h4 id="长期“不明原因”的中、高热"><a class="header-anchor" href="#长期“不明原因”的中、高热">¶</a>长期“不明原因”的中、高热</h4> +<p>系指发热持续3周以上,体温多次超过38.3℃,经过至少1周深入细致的检查仍不能确诊的一组疾病,主要有感染、恶性肿瘤与结缔组织-血管性疾病三大类</p> <ol> <li>感染:引起发热待查的感染性疾病中主要由细菌感染所致,而任何一种致病菌或条件致病菌,或L-型细菌性感染均可分为全身性与局部性感染。全身性感染以伤寒与副伤寒、粟粒型结核与播散性结核(包括腹膜、肠、肠系膜淋巴结、肝、肾、胸膜和肺与肺门淋巴结结核)、脓毒症与感染性心内膜炎、布鲁菌病、黑热病、急性血吸虫病、旋毛虫病等;局部性感染以肝脓肿、胆道与泌尿生殖道感染、腹腔内脓肿(包括肝下、膈下、结肠旁、阑尾周围、腹膜后、盆腔脓肿等)为常见。局部性感染易被临床忽略。</li> <li>恶性肿瘤:也是长期发热的常见原因。最常见的为原发性肝癌、淋巴瘤、恶性组织细胞病与白血病,其次为实质性恶性肿瘤如肺癌、肾癌、甲状腺癌等。</li> <li>结缔组织,血管性疾病:也是较常见原因之一,大多伴有关节痛、皮肤、心、肾等多系统病变引起的相应症状与体征,但少数病例在典型症状出现前数周或数月可出现发热。此类疾病以系统性红斑狼疮、成人少年型类风湿关节炎、多动脉炎、皮肌炎、混合性结缔组织病、风湿热等常见。</li> <li>其他:肉芽肿性疾病(肉芽肿性肝炎、结节病、局限性回肠炎等)、药物热、伪装热、体腔积血如血胸、血腹、肺梗死等。</li> </ol> -<h4 id="长期低热"><a href="#长期低热" class="headerlink" title="长期低热"></a>长期低热</h4><p>口腔温度在37.5℃至38.4℃,持续4周以上者。在诊断为长期低热时,必须先了解其正常体温,排除生理或功能性因素,并排除高温环境等影响,如在高温车间的纺织女工中,有长期低热者可达10%以上。长期低热由感染性疾病引起者占40%,非感染性疾病占57%,原因不明占3%。长期低热的原因可分为器质性与功能性两大类。</p> +<h4 id="长期低热"><a class="header-anchor" href="#长期低热">¶</a>长期低热</h4> +<p>口腔温度在37.5℃至38.4℃,持续4周以上者。在诊断为长期低热时,必须先了解其正常体温,排除生理或功能性因素,并排除高温环境等影响,如在高温车间的纺织女工中,有长期低热者可达10%以上。长期低热由感染性疾病引起者占40%,非感染性疾病占57%,原因不明占3%。长期低热的原因可分为器质性与功能性两大类。</p> +<ol> +<li>器质性低热: <ol> -<li>器质性低热:<ol> <li>慢性感染:如结核病、肝脏疾病、慢性肾盂肾炎、慢性胆道感染以及各种病灶感染(鼻窦炎、牙根脓肿、前列腺炎、慢性盆腔炎、肛门周围脓肿等)。</li> <li>结缔组织疾病:如风湿热、类风湿关节炎、系统性红斑狼疮等。</li> <li>内分泌疾病:如甲亢、嗜铬细胞瘤等。</li> <li>恶性肿瘤:早期淋巴瘤、实质性癌肿转移等。</li> </ol> </li> -<li>功能性低热<ol> +<li>功能性低热 +<ol> <li>生理性低热:月经前期低热、妊娠期低热等。</li> -<li>神经功能性低热:多见于青年女性,长期低热可长达数月或数年。有些患者低热有季节性,出现于夏季(谓之夏季低热),且每年如此。体温在一昼夜内波动幅度较小,常不超过0.5℃,且口腔、腋窝与直肠温度差不大,甚至可出现腋温大于口温,口温大于肛温或腋温大于肛温的反常现象,两侧腋温可相差1℃以上。体温昼夜规律失常。患者常伴有脸色潮红、皮肤划痕症、心动过速等自主神经功能紊乱或神经症色彩。但患者一般情况好,体重无变化,虽经各种药物治疗无效,但不经治疗也可自行消退。神经功能性低热较常见,约占长期低热的1/3,预后良好。</li> +<li>神经功能性低热:多见于青年女性,长期低热可长达数月或数年。有些患者低热有季节性,出现于夏季(谓之夏季低热),且每年如此。体温在一昼夜内波动幅度较小,常不超过0.5℃,且口腔、腋窝与直肠温度差不大,甚至可出现腋温大于口温,口温大于肛温或腋温大于肛温的反常现象,两侧腋温可相差1℃以上。体温昼夜规律失常。患者常伴有脸色潮红、皮肤划痕症、心动过速等自主神经功能紊乱或神经症色彩。但患者一般情况好,体重无变化,虽经各种药物治疗无效,但不经治疗也可自行消退。神经功能性低热较常见,约占长期低热的1/3,预后良好。</li> <li>感染后低热:急性病毒或细菌感染得到控制后,高热消退,但可出现持续较久的低热,并伴有乏力,纳差等现象。此种发热可能与体温调节中枢功能失常或自主神经功能紊乱有关。</li> </ol> </li> </ol> -<h4 id="超高热危象的识别与诊断"><a href="#超高热危象的识别与诊断" class="headerlink" title="超高热危象的识别与诊断"></a>超高热危象的识别与诊断</h4><p>超高热系指发热超过41℃以上,主要见于体温调节中枢功能障碍,超高热(体温>41℃)是超高热危象的必有表现。</p> +<h4 id="超高热危象的识别与诊断"><a class="header-anchor" href="#超高热危象的识别与诊断">¶</a>超高热危象的识别与诊断</h4> +<p>超高热系指发热超过41℃以上,主要见于体温调节中枢功能障碍,超高热(体温>41℃)是超高热危象的必有表现。</p> <p>有以下各种原因:</p> <ol> <li>中暑或日射病</li> @@ -4110,7 +4519,8 @@ await prisma.$transaction(async tx => { </ol> <p>不论病因如何,超高热对细胞膜与细胞内结构有直接损害作用,当深部体温>41℃时细胞线粒体的氧化磷酸化出现障碍,可引起永久性脑损害;42~43℃持续数分钟细胞会陷入不可逆的损害,涉及全身各种细胞,尤以脑、心、肝、肾的变化最为突出,容易造成脑水肿颅内压升高,抽搐、昏迷,心、肝、肾、肺功能衰竭,DIC等多脏器功能衰竭。超高热危象的诊断要点是:</p> <ol> -<li><p>超高热时伴有多脏器功能受损害的表现:</p> +<li> +<p>超高热时伴有多脏器功能受损害的表现:</p> <ol> <li>心血管系统:低血压休克、心功能不全、心肌缺血与心律失常等。</li> <li>中枢神经系统:体温越高对中枢神经系统损害越重,症状出现越早;包括不同程度的意识障碍如谵妄、嗜睡、昏迷、抽搐、大小便失禁、脑膜刺激征、瘫痪、病理反射阳性、脑疝、视神经乳头水肿等。</li> @@ -4121,27 +4531,36 @@ await prisma.$transaction(async tx => { <li>其他表现:如横纹肌溶解可致血肌酸磷酸激酶(CK)增高等。</li> </ol> </li> -<li><p>原发病的表现:<br>如中毒性菌痢的腹泻、脓血便;乙脑时的抽搐、昏迷等。</p> +<li> +<p>原发病的表现:<br> +如中毒性菌痢的腹泻、脓血便;乙脑时的抽搐、昏迷等。</p> </li> </ol> -<h2 id="定义"><a href="#定义" class="headerlink" title="定义"></a>定义</h2><p>发热(fever)是指机体在致热原作用下或各种原因引起体温调节中枢的功能障碍时,体温升高超出正常范围。见于各种全身性和局部性感染以及许多非感染性疾病(如肿瘤与结缔组织病等),它是内科急诊中最常见的症状。一般而言,当腋下、口腔或直肠内温度分别超过37℃、37.3℃和37.6℃,并且24小时内温度差波动在1℃以上,可称为发热。按照发热的高低,可分为:</p> +<h2 id="定义"><a class="header-anchor" href="#定义">¶</a>定义</h2> +<p>发热(fever)是指机体在致热原作用下或各种原因引起体温调节中枢的功能障碍时,体温升高超出正常范围。见于各种全身性和局部性感染以及许多非感染性疾病(如肿瘤与结缔组织病等),它是内科急诊中最常见的症状。一般而言,当腋下、口腔或直肠内温度分别超过37℃、37.3℃和37.6℃,并且24小时内温度差波动在1℃以上,可称为发热。按照发热的高低,可分为:</p> <ol> <li>低热:37.4~38℃</li> <li>中度发热:38.1~39℃</li> <li>高热:39.1~41℃</li> <li>超高热;41℃以上。</li> </ol> -<h2 id="后果"><a href="#后果" class="headerlink" title="后果"></a>后果</h2><p>超高热或过高热危象(extreme pyrexic crisis,EPC)是指过高热若不及时处理,使脑、心、肾等重要器官受到严重损害,出现抽搐、昏迷、休克、出血、心脏、呼吸和肾衰竭等危及生命的状态。若抢救不力,常于数小时内死亡。</p> -<h2 id="人体散热方式"><a href="#人体散热方式" class="headerlink" title="人体散热方式"></a>人体散热方式</h2><p>人体散热主要有辐射、蒸发、对流及传导物理过程,当周围温度低于皮肤温度时,热即从皮肤辐射散热;其次是体内热量传导至皮肤周围空气层,经对流散热。当周围温度超过体温时,主要依靠汗液蒸发,体热从皮肤、呼吸道和大小便3处消散,以皮肤散热最为重要。当室温在23~25℃时,体热通过皮肤辐射、对流、传导散热占70%;当室温高达31~32℃时,出汗蒸发即成为散热主要方式。皮肤血管内血流量越大,散热速度越快;</p> +<h2 id="后果"><a class="header-anchor" href="#后果">¶</a>后果</h2> +<p>超高热或过高热危象(extreme pyrexic crisis,EPC)是指过高热若不及时处理,使脑、心、肾等重要器官受到严重损害,出现抽搐、昏迷、休克、出血、心脏、呼吸和肾衰竭等危及生命的状态。若抢救不力,常于数小时内死亡。</p> +<h2 id="人体散热方式"><a class="header-anchor" href="#人体散热方式">¶</a>人体散热方式</h2> +<p>人体散热主要有辐射、蒸发、对流及传导物理过程,当周围温度低于皮肤温度时,热即从皮肤辐射散热;其次是体内热量传导至皮肤周围空气层,经对流散热。当周围温度超过体温时,主要依靠汗液蒸发,体热从皮肤、呼吸道和大小便3处消散,以皮肤散热最为重要。当室温在23~25℃时,体热通过皮肤辐射、对流、传导散热占70%;当室温高达31~32℃时,出汗蒸发即成为散热主要方式。皮肤血管内血流量越大,散热速度越快;</p> <p><strong>体表温度越高,则散热也越迅速。</strong></p> -<h2 id="致热原"><a href="#致热原" class="headerlink" title="致热原"></a>致热原</h2><p>致热原是一类能引起恒温动物体温异常升高的物质的总称。可分为外源性和内源性两类</p> +<h2 id="致热原"><a class="header-anchor" href="#致热原">¶</a>致热原</h2> +<p>致热原是一类能引起恒温动物体温异常升高的物质的总称。可分为外源性和内源性两类</p> <ol> -<li><p>外源性致热原: 各种病原体如细菌、病毒、立克次体、衣原体、螺旋体、原虫和寄生虫等的毒素及其代谢产物,尤以内毒素(多属脂多糖类物质)最为重要,其次是原胆烷醇酮、多核苷酸、抗原-抗体复合物等。</p> +<li> +<p>外源性致热原: 各种病原体如细菌、病毒、立克次体、衣原体、螺旋体、原虫和寄生虫等的毒素及其代谢产物,尤以内毒素(多属脂多糖类物质)最为重要,其次是原胆烷醇酮、多核苷酸、抗原-抗体复合物等。</p> </li> -<li><p>内源性致热原: 外源性致热原一般不能直接作用于体温调节中枢引起发热,但能刺激和激活主要存在于白细胞、单核细胞和组织吞噬细胞内的内源性致热原前体,于短期内合成新的mRNA和致热原,这些具有活性的内源性致热原可能是通过某些生物活性物质如前列腺素、单胺、cAMP、钙钠比值、内啡肽等作为中介,提高体温调节中枢调定点而引起发热。</p> +<li> +<p>内源性致热原: 外源性致热原一般不能直接作用于体温调节中枢引起发热,但能刺激和激活主要存在于白细胞、单核细胞和组织吞噬细胞内的内源性致热原前体,于短期内合成新的mRNA和致热原,这些具有活性的内源性致热原可能是通过某些生物活性物质如前列腺素、单胺、cAMP、钙钠比值、内啡肽等作为中介,提高体温调节中枢调定点而引起发热。</p> </li> </ol> -<h3 id="发生机制"><a href="#发生机制" class="headerlink" title="发生机制"></a>发生机制</h3><p>因产热、散热异常所致。因产热过多引起的发热不多,主要见于剧烈运动后、癫痫持续状态和甲亢危象时,一般持续不久。广泛性皮肤病、阿托品中毒时出汗功能障碍,散热减少引起发热,主要见于炎热季节。大量失水、失血常伴有发热,尤其多见于小儿,出现所谓“失水热”,是由于血容量减少、散热减少。心脏病患者也可有发热,主要由于肺部充血和肺部感染或有风湿活动或血栓形成外,在心衰阶段的发热,则与皮肤水肿引起散热减少有关。中枢神经性高温以中暑最为典型,也可由脑出血、脑炎等引起。由于中枢神经系统遭受严重伤害,下丘脑丧失调温能力而衰竭,每有骤升的超高温,达41℃或以上,同时交感神经受抑制,以皮肤干燥无汗为特征。</p> +<h3 id="发生机制"><a class="header-anchor" href="#发生机制">¶</a>发生机制</h3> +<p>因产热、散热异常所致。因产热过多引起的发热不多,主要见于剧烈运动后、癫痫持续状态和甲亢危象时,一般持续不久。广泛性皮肤病、阿托品中毒时出汗功能障碍,散热减少引起发热,主要见于炎热季节。大量失水、失血常伴有发热,尤其多见于小儿,出现所谓“失水热”,是由于血容量减少、散热减少。心脏病患者也可有发热,主要由于肺部充血和肺部感染或有风湿活动或血栓形成外,在心衰阶段的发热,则与皮肤水肿引起散热减少有关。中枢神经性高温以中暑最为典型,也可由脑出血、脑炎等引起。由于中枢神经系统遭受严重伤害,下丘脑丧失调温能力而衰竭,每有骤升的超高温,达41℃或以上,同时交感神经受抑制,以皮肤干燥无汗为特征。</p> ]]></content> <tags> <tag>Medicine</tag> @@ -4152,21 +4571,25 @@ await prisma.$transaction(async tx => { <title>呋塞米</title> <url>/2023/03/14/%E5%91%8B%E5%A1%9E%E7%B1%B3/</url> <content><![CDATA[<p><strong>孕妇禁用,小儿慎用!!!!</strong></p> -<h2 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h2><p>口服吸收迅速,生物利用度约为60%,约30分钟起效,1~2小时达高峰,持续6~8小时。静脉注射5~10分钟起效,30分钟达高峰,t1/2约1小时,维持4~6小时。血浆蛋白结合率约98%。大部分以原形经近曲小管有机酸分泌系统随尿排出。反复给药不易蓄积。 </p> +<h2 id="简介"><a class="header-anchor" href="#简介">¶</a>简介</h2> +<p>口服吸收迅速,生物利用度约为60%,约30分钟起效,1~2小时达高峰,持续6~8小时。静脉注射5~10分钟起效,30分钟达高峰,t1/2约1小时,维持4~6小时。血浆蛋白结合率约98%。大部分以原形经近曲小管有机酸分泌系统随尿排出。反复给药不易蓄积。</p> <p>主要作用有两个</p> <ol> <li>利尿:作用强大、迅速而短暂,但个体差异明显,应注意剂量个体化。而且利尿作用不受酸碱平衡失调及电解质紊乱的影响。需要注意的是,这个药容易引起低血钾、低盐综合征及低氯性碱中毒。低血钾最常见,还促进Ca2+、Mg2+排出,而抑制尿酸排出。</li> <li>扩张血管:能扩张肾血管,增加肾血流量,改变肾皮质内血流分布,还能扩张小静脉,减少回心血量,减轻心脏负荷,降低左室充盈压,减轻肺水肿。扩血管机制可能与本药促进前列腺素酶合成,抑制其分解有关。</li> </ol> -<p>临床上用于治疗心脏性水肿、肾性水肿、肝硬化腹水、机能障碍或血管障碍所引起的周围性水肿,并可促使上部尿道结石的排出。其利尿作用迅速、强大,多用于其它利尿药无效的严重病例。由于水、电解质丢失明显等原因,故不宜常规使用。静脉给药(20~80mg)可治疗肺水肿和脑水肿。药物中毒时可用以加速毒物的排泄。 </p> -<h2 id="用药"><a href="#用药" class="headerlink" title="用药"></a>用药</h2><p>肌注或静注隔日1次,每次mg,必要时亦可1日~2次。1日量视需要可增至120mg。静注必须缓慢,不宜与其他药物混合注射。儿童用量酌减(2)口服开始时每日~40mg,以后根据需要可增至每日~120mg。当每日剂量超过40mg时,可以每4小时1次分服。儿童口服量开始按1~2mg/kg,再视情况酌增。长期(7~10日)用药后利尿作用消失,故需长期应用者,宜采取间歇疗法:给药1~3日,停药2~4日。 </p> -<h2 id="不良反应"><a href="#不良反应" class="headerlink" title="不良反应"></a>不良反应</h2><ol> -<li>水与电解质紊乱,常为过度利尿所引起,表现为低血容量、低血钾、低血钠、低氯性碱血症,长期应用还可引起低血镁。 </li> +<p>临床上用于治疗心脏性水肿、肾性水肿、肝硬化腹水、机能障碍或血管障碍所引起的周围性水肿,并可促使上部尿道结石的排出。其利尿作用迅速、强大,多用于其它利尿药无效的严重病例。由于水、电解质丢失明显等原因,故不宜常规使用。静脉给药(20~80mg)可治疗肺水肿和脑水肿。药物中毒时可用以加速毒物的排泄。</p> +<h2 id="用药"><a class="header-anchor" href="#用药">¶</a>用药</h2> +<p>肌注或静注隔日1次,每次mg,必要时亦可1日~2次。1日量视需要可增至120mg。静注必须缓慢,不宜与其他药物混合注射。儿童用量酌减(2)口服开始时每日~40mg,以后根据需要可增至每日~120mg。当每日剂量超过40mg时,可以每4小时1次分服。儿童口服量开始按1~2mg/kg,再视情况酌增。长期(7~10日)用药后利尿作用消失,故需长期应用者,宜采取间歇疗法:给药1~3日,停药2~4日。</p> +<h2 id="不良反应"><a class="header-anchor" href="#不良反应">¶</a>不良反应</h2> +<ol> +<li>水与电解质紊乱,常为过度利尿所引起,表现为低血容量、低血钾、低血钠、低氯性碱血症,长期应用还可引起低血镁。</li> <li>耳毒性,表现为耳鸣、听力减退或暂时性耳聋,呈剂量依赖性。耳毒性的发生机制可能与药物引起内耳淋巴液电解质成分改变有关。肾功能不全或同时使用其他耳毒性药物,如并用氨基糖苷类抗生素时较易发生耳毒性。</li> <li>高尿酸血症,袢利尿药可能造成高尿酸血症,并引发痛风。</li> <li>其他,可有恶心、呕吐、大剂量时尚可出现胃肠出血。</li> </ol> -<h2 id="注意"><a href="#注意" class="headerlink" title="注意"></a>注意</h2><ol> +<h2 id="注意"><a class="header-anchor" href="#注意">¶</a>注意</h2> +<ol> <li>可能出现轻微恶心、腹泻、药疹、瘙痒、视力模糊等副作用,有时可发生起立性眩晕、乏力、疲倦、肌肉痉挛、口渴,少数病例有白细胞减少,个别病例出现血小板减少、多形性红斑、直立性低血压。长期应用可致胃及十二指肠溃疡。</li> <li>由于能减少尿酸排出,故多次应用后能产生尿酸过多症,个别病人长期应用可产生急性痛风。痛风病患者慎用。</li> <li>糖尿病患者应用后可使血糖增高;糖尿病患者慎用。尽管其升血糖远较噻嗪类利尿药弱,但与降血糖药合并应用时,仍有使血糖增高的可能。</li> @@ -4179,9 +4602,11 @@ await prisma.$transaction(async tx => { <li>因结构上是与氯噻嗪结构相似的磺胺型化合物,能降低动脉对升压胺(如去甲肾上腺素)的反应,并能增加筒箭毒硷的肌松弛及麻痹作用,故手术前一周应停用。(11)低钾血症、超量服用洋地黄、肝昏迷患者禁用。晚期肝硬化患者慎用。</li> <li>大剂量静注过快时,可出现听力减退或暂时性耳聋。不宜与氨基糖昔类抗生素配伍应用,因更易引起听力减退。</li> </ol> -<h2 id="其他"><a href="#其他" class="headerlink" title="其他"></a>其他</h2><p>螺内酯为《2018版中国国家基本药物目录》在列药物,“基本药物”指的是能够满足基本医疗卫生需求,剂型适宜、保证供应、基层能够配备、国民能够公平获得的药品。</p> -<h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><ul> -<li><a href="https://www.yixue.com/%E5%91%8B%E5%A1%9E%E7%B1%B3">https://www.yixue.com/%E5%91%8B%E5%A1%9E%E7%B1%B3</a></li> +<h2 id="其他"><a class="header-anchor" href="#其他">¶</a>其他</h2> +<p>螺内酯为《2018版中国国家基本药物目录》在列药物,“基本药物”指的是能够满足基本医疗卫生需求,剂型适宜、保证供应、基层能够配备、国民能够公平获得的药品。</p> +<h2 id="参考"><a class="header-anchor" href="#参考">¶</a>参考</h2> +<ul> +<li><a href="https://www.yixue.com/%E5%91%8B%E5%A1%9E%E7%B1%B3">https://www.yixue.com/呋塞米</a></li> </ul> ]]></content> <tags> @@ -4191,51 +4616,50 @@ await prisma.$transaction(async tx => { <entry> <title>在F#中处理复杂依赖注入的实践指南</title> <url>/2025/03/31/%E5%9C%A8F-%E4%B8%AD%E5%A4%84%E7%90%86%E5%A4%8D%E6%9D%82%E4%BE%9D%E8%B5%96%E6%B3%A8%E5%85%A5%E7%9A%84%E5%AE%9E%E8%B7%B5%E6%8C%87%E5%8D%97/</url> - <content><![CDATA[<h2 id="一、传统手艺:Partial-Application"><a href="#一、传统手艺:Partial-Application" class="headerlink" title="一、传统手艺:Partial Application"></a>一、传统手艺:Partial Application</h2><p>在函数式编程中,Partial Application 是传递依赖的常用方式。例如:</p> + <content><![CDATA[<h2 id="一、传统手艺:Partial-Application"><a class="header-anchor" href="#一、传统手艺:Partial-Application">¶</a>一、传统手艺:Partial Application</h2> +<p>在函数式编程中,Partial Application 是传递依赖的常用方式。例如:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> foo bar baz request <span class="operator">=</span> <span class="operator">...</span></span><br><span class="line"><span class="keyword">let</span> wired <span class="operator">=</span> foo dependency1 dependency2</span><br><span class="line"><span class="keyword">let</span> response <span class="operator">=</span> wired request</span><br></pre></td></tr></table></figure> - -<p>优点: </p> +<p>优点:</p> <ul> -<li>无需框架或反射,直接通过函数参数传递依赖。 </li> +<li>无需框架或反射,直接通过函数参数传递依赖。</li> <li>符合函数式编程的纯函数理念。</li> </ul> -<p>缺点: </p> +<p>缺点:</p> <ul> -<li>参数爆炸:当功能扩展时,参数数量激增(如日志、数据库、加密等)。 </li> -<li>维护困难:新增依赖需修改所有调用点的参数传递。 </li> +<li>参数爆炸:当功能扩展时,参数数量激增(如日志、数据库、加密等)。</li> +<li>维护困难:新增依赖需修改所有调用点的参数传递。</li> <li>隐式依赖:难以从函数签名直接区分核心参数与辅助依赖。</li> </ul> <hr> -<h2 id="二、结构化方法:单一环境参数(env)"><a href="#二、结构化方法:单一环境参数(env)" class="headerlink" title="二、结构化方法:单一环境参数(env)"></a>二、结构化方法:单一环境参数(<code>env</code>)</h2><p>为解决参数爆炸问题,可将依赖封装为单一环境对象<code>env</code>,并通过接口约束访问权限:</p> +<h2 id="二、结构化方法:单一环境参数(env)"><a class="header-anchor" href="#二、结构化方法:单一环境参数(env)">¶</a>二、结构化方法:单一环境参数(<code>env</code>)</h2> +<p>为解决参数爆炸问题,可将依赖封装为单一环境对象<code>env</code>,并通过接口约束访问权限:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="meta">[<Interface>]</span> <span class="keyword">type</span> <span class="title class_">ILog</span> <span class="operator">=</span> <span class="keyword">abstract</span> Logger<span class="operator">:</span> ILogger</span><br><span class="line"><span class="meta">[<Interface>]</span> <span class="keyword">type</span> <span class="title class_">IDb</span> <span class="operator">=</span> <span class="keyword">abstract</span> Database<span class="operator">:</span> IDatabase</span><br><span class="line"></span><br><span class="line"><span class="keyword">module</span> Log <span class="operator">=</span></span><br><span class="line"> <span class="keyword">let</span> info (env<span class="operator">:</span> #ILog) <span class="operator">=</span> env.Logger.Info(<span class="string">"Message"</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">module</span> Db <span class="operator">=</span></span><br><span class="line"> <span class="keyword">let</span> fetchUser (env<span class="operator">:</span> #IDb) <span class="operator">=</span> env.Database.Query(<span class="operator">...</span>)</span><br></pre></td></tr></table></figure> - -<p>优点: </p> +<p>优点:</p> <ul> -<li>显式依赖声明:函数签名仅需<code>env</code>参数,编译器验证接口实现。 </li> -<li>模块化隔离:各模块仅声明所需接口(如<code>ILog</code>、<code>IDb</code>),避免全局依赖。 </li> +<li>显式依赖声明:函数签名仅需<code>env</code>参数,编译器验证接口实现。</li> +<li>模块化隔离:各模块仅声明所需接口(如<code>ILog</code>、<code>IDb</code>),避免全局依赖。</li> <li>易于测试:通过模拟<code>env</code>实现单元测试,无需依赖具体实现。</li> </ul> -<p>应用场景: </p> +<p>应用场景:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> changePass env req <span class="operator">=</span> <span class="keyword">task</span> {</span><br><span class="line"> <span class="keyword">let!</span> user <span class="operator">=</span> Db.fetchUser env req.UserId</span><br><span class="line"> Log.info env <span class="string">"Processing user: %i"</span> user.Id</span><br><span class="line"> <span class="operator">...</span></span><br><span class="line">}</span><br></pre></td></tr></table></figure> - <hr> -<h2 id="三、Reader-Monad"><a href="#三、Reader-Monad" class="headerlink" title="三、Reader Monad"></a>三、Reader Monad</h2><p>为消除显式的<code>env</code>传递,可引入 Reader Monad,将环境隐式注入计算流程:</p> +<h2 id="三、Reader-Monad"><a class="header-anchor" href="#三、Reader-Monad">¶</a>三、Reader Monad</h2> +<p>为消除显式的<code>env</code>传递,可引入 Reader Monad,将环境隐式注入计算流程:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="meta">[<Struct>]</span> <span class="keyword">type</span> <span class="title class_">Effect</span><span class="operator"><</span><span class="symbol">'env</span>, <span class="symbol">'out</span><span class="operator">></span> <span class="operator">=</span> Effect <span class="keyword">of</span> (<span class="symbol">'env</span> <span class="operator">-></span> <span class="symbol">'out</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">module</span> Effect <span class="operator">=</span></span><br><span class="line"> <span class="keyword">let</span> run env (Effect fn) <span class="operator">=</span> fn env</span><br><span class="line"> <span class="keyword">let</span> bind f effect <span class="operator">=</span> Effect (<span class="keyword">fun</span> env <span class="operator">-></span> run env (f (run env effect)))</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">EffectBuilder</span>() <span class="operator">=</span></span><br><span class="line"> <span class="keyword">member</span> __.Bind(e, f) <span class="operator">=</span> Effect.bind f e</span><br><span class="line"> <span class="keyword">member</span> __.Return(x) <span class="operator">=</span> Effect (<span class="keyword">fun</span> _ <span class="operator">-></span> x)</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> effect <span class="operator">=</span> EffectBuilder()</span><br></pre></td></tr></table></figure> - <p>然后:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> changePass req <span class="operator">=</span> <span class="keyword">effect</span> {</span><br><span class="line"> <span class="keyword">let!</span> user <span class="operator">=</span> Db.fetchUser req.UserId</span><br><span class="line"> <span class="keyword">let!</span> salt <span class="operator">=</span> Random.bytes <span class="number">32</span></span><br><span class="line"> <span class="keyword">do!</span> Log.info <span class="string">"Password updated for user %i"</span> user.Id</span><br><span class="line"> <span class="keyword">return</span> <span class="literal">Ok</span>()</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - -<p>优点: </p> +<p>优点:</p> <ul> -<li>隐式依赖管理:通过<code>effect</code>计算表达式自动传递<code>env</code>,减少样板代码。 </li> -<li>组合性:支持与其他计算表达式(如<code>async</code>/<code>task</code>)结合,处理异步操作。</li> +<li>隐式依赖管理:通过<code>effect</code>计算表达式自动传递<code>env</code>,减少样板代码。</li> +<li>组合性:支持与其他计算表达式(如<code>async</code>/<code>task</code>)结合,处理异步操作。</li> </ul> -<p>缺点: </p> +<p>缺点:</p> <ul> -<li>性能开销:频繁的闭包创建和间接调用可能导致性能下降。 </li> +<li>性能开销:频繁的闭包创建和间接调用可能导致性能下降。</li> <li>生态兼容性:需自定义计算表达式,与现有异步框架集成复杂。</li> </ul> -<h2 id="Refs"><a href="#Refs" class="headerlink" title="Refs."></a>Refs.</h2><ul> +<h2 id="Refs"><a class="header-anchor" href="#Refs">¶</a>Refs.</h2> +<ul> <li>Spring的构造器注入</li> <li>Blazor的DI实现</li> </ul> @@ -4248,24 +4672,33 @@ await prisma.$transaction(async tx => { <title>奥司他韦</title> <url>/2023/03/05/%E5%A5%A5%E5%8F%B8%E4%BB%96%E9%9F%A6/</url> <content><![CDATA[<p><img src="/img/%E5%8C%BB%E5%AD%A6/%E5%A5%A5%E5%8F%B8%E4%BB%96%E9%9F%A6.jpg" alt="奥司他韦.jpg"></p> -<p>目前市场上销售的达菲为罗氏制药独家生产的抗流感药物,其通用名称为磷酸奥司他韦(Oseltamivirphosphate)。奥司他韦(Oseltamivir)于1999年在瑞士上市,2001年10月在我国上市。达菲是一种非常有效的流感治疗用药,并且可以大大减少并发症(主要是气管与支气管炎、肺炎、咽炎等)的发生和抗生素的使用,因而是目前治疗流感的最常用药物之一,也是公认的抗禽流感、甲型H1N1病毒最有效的药物之一。 </p> -<h2 id="主要原理"><a href="#主要原理" class="headerlink" title="主要原理"></a>主要原理</h2><p>奥司他韦口服后经肝脏和肠道酯酶迅速催化转化为其活性代谢物奥司他韦羧酸,奥司他韦羧酸的构型与神经氨酸的过渡态相似,能够竞争性地与流感病毒神经氨酸酶(NA,neu-raminidase,也有称作神经氨酸苷酶)的活动位点结合,因而是一种强效的高选择性的流感病毒NA抑制剂(NAIs),它主要通过干扰病毒从被感染的宿主细胞中释放,从而减少甲型或乙型流感病毒的传播。 </p> -<h2 id="特殊人群"><a href="#特殊人群" class="headerlink" title="特殊人群"></a>特殊人群</h2><ol> -<li><p>对不同程度的肾功能不全患者给予100mg磷酸奥司他韦,每日两次,服用五天,显示活性代谢产物水平与降低肾功能成反比。对肌酐清除率小于30ml/min的患者建议做剂量调整。目前没有研究数据指导肾功能衰竭患者的用药(肌酐清除小于10ml/nin),所以对该人群用药时要慎重。</p> +<p>目前市场上销售的达菲为罗氏制药独家生产的抗流感药物,其通用名称为磷酸奥司他韦(Oseltamivirphosphate)。奥司他韦(Oseltamivir)于1999年在瑞士上市,2001年10月在我国上市。达菲是一种非常有效的流感治疗用药,并且可以大大减少并发症(主要是气管与支气管炎、肺炎、咽炎等)的发生和抗生素的使用,因而是目前治疗流感的最常用药物之一,也是公认的抗禽流感、甲型H1N1病毒最有效的药物之一。</p> +<h2 id="主要原理"><a class="header-anchor" href="#主要原理">¶</a>主要原理</h2> +<p>奥司他韦口服后经肝脏和肠道酯酶迅速催化转化为其活性代谢物奥司他韦羧酸,奥司他韦羧酸的构型与神经氨酸的过渡态相似,能够竞争性地与流感病毒神经氨酸酶(NA,neu-raminidase,也有称作神经氨酸苷酶)的活动位点结合,因而是一种强效的高选择性的流感病毒NA抑制剂(NAIs),它主要通过干扰病毒从被感染的宿主细胞中释放,从而减少甲型或乙型流感病毒的传播。</p> +<h2 id="特殊人群"><a class="header-anchor" href="#特殊人群">¶</a>特殊人群</h2> +<ol> +<li> +<p>对不同程度的肾功能不全患者给予100mg磷酸奥司他韦,每日两次,服用五天,显示活性代谢产物水平与降低肾功能成反比。对肌酐清除率小于30ml/min的患者建议做剂量调整。目前没有研究数据指导肾功能衰竭患者的用药(肌酐清除小于10ml/nin),所以对该人群用药时要慎重。</p> </li> -<li><p>口服磷酸奥司他韦后。肝功能不全患者并没有象预期那样体内奥司他韦水平增高或其活性代谢产物水平降低。</p> +<li> +<p>口服磷酸奥司他韦后。肝功能不全患者并没有象预期那样体内奥司他韦水平增高或其活性代谢产物水平降低。</p> </li> -<li><p>给予相同剂量的磷酸奥司他韦,同年轻人相比,老年人(年龄在65—78岁间)的稳态代谢物水平比年轻人高25~35%,而两个人群药物半衰期很相似。考虑到药物暴露量和耐受力,老年人不必调整剂量。</p> +<li> +<p>给予相同剂量的磷酸奥司他韦,同年轻人相比,老年人(年龄在65—78岁间)的稳态代谢物水平比年轻人高25~35%,而两个人群药物半衰期很相似。考虑到药物暴露量和耐受力,老年人不必调整剂量。</p> </li> -<li><p>对一小组5~18岁儿童给予单剂2mg/kg的粉末剂,口服建立药代曲线,数据显示儿童年龄越小,对药物前体和其活性代谢产物的清除越快,人体对每mg/kg计量单位的承受越少。比如给予5-8岁儿童2mg/kg的剂量,若要达到可比性。即相当于要给予成年人单剂75mg奥司他韦(大约为1mg/kg)。年龄相差越小,儿童与成年人对每一单位mg/kg剂量的代谢差别越小。比如大于12岁的儿童与成年人在药代动力学方面就已经很相似了。</p> +<li> +<p>对一小组5~18岁儿童给予单剂2mg/kg的粉末剂,口服建立药代曲线,数据显示儿童年龄越小,对药物前体和其活性代谢产物的清除越快,人体对每mg/kg计量单位的承受越少。比如给予5-8岁儿童2mg/kg的剂量,若要达到可比性。即相当于要给予成年人单剂75mg奥司他韦(大约为1mg/kg)。年龄相差越小,儿童与成年人对每一单位mg/kg剂量的代谢差别越小。比如大于12岁的儿童与成年人在药代动力学方面就已经很相似了。</p> </li> </ol> -<h2 id="不良反应"><a href="#不良反应" class="headerlink" title="不良反应"></a>不良反应</h2><p>在罗氏提交美国联邦食品和药品管理局的申报材料中指出,奥司他韦(达菲)主要的不良反应显示为消化道的不适,包括恶心、呕吐、腹泻、腹痛等,其次是呼吸系统的不良反应,包括支气管炎、咳嗽等,此外还有中枢神经系统的不良反应,如眩晕、头痛、失眠、疲劳等。</p> +<h2 id="不良反应"><a class="header-anchor" href="#不良反应">¶</a>不良反应</h2> +<p>在罗氏提交美国联邦食品和药品管理局的申报材料中指出,奥司他韦(达菲)主要的不良反应显示为消化道的不适,包括恶心、呕吐、腹泻、腹痛等,其次是呼吸系统的不良反应,包括支气管炎、咳嗽等,此外还有中枢神经系统的不良反应,如眩晕、头痛、失眠、疲劳等。</p> <p>在2004年1月,FDA还发出对于奥司他韦的消费警讯,声称由于1岁以内幼儿血脑屏障发育不完全,奥司他韦应用于幼儿可能造成脑内药物浓度过高,形成潜在的安全问题。</p> <p>2005年有日本媒体报道日本青少年服用奥斯他韦后自杀并有精神异常反应,此后日本先后报道数十例此类不良反应,此后世界各地媒体纷纷转载报道,引起公众关注。2005年11月FDA就这一反应作出报告,认为没有证据证明奥斯他韦可以导致精神异常,日本的不良反应病例系大众媒体报道后经心理暗示作用引起的群体性臆症。</p> -<h2 id="其他"><a href="#其他" class="headerlink" title="其他"></a>其他</h2><p>需要注意的是,奥司他韦是通过抑制病毒的复制而起到治疗流感作用的,如果人体没有感染病毒,吃了“达菲”也是没有任何作用的。也就是说,“达菲”是在体内存在病毒的前提下起到杀灭病毒的作用,它不可能抵抗病毒侵入人体。</p> -<h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><ul> -<li><a href="https://www.yixue.com/%e8%be%be%e8%8f%b2">https://www.yixue.com/%e8%be%be%e8%8f%b2</a></li> +<h2 id="其他"><a class="header-anchor" href="#其他">¶</a>其他</h2> +<p>需要注意的是,奥司他韦是通过抑制病毒的复制而起到治疗流感作用的,如果人体没有感染病毒,吃了“达菲”也是没有任何作用的。也就是说,“达菲”是在体内存在病毒的前提下起到杀灭病毒的作用,它不可能抵抗病毒侵入人体。</p> +<h2 id="参考"><a class="header-anchor" href="#参考">¶</a>参考</h2> +<ul> +<li><a href="https://www.yixue.com/%e8%be%be%e8%8f%b2">https://www.yixue.com/达菲</a></li> </ul> ]]></content> <tags> @@ -4279,11 +4712,13 @@ await prisma.$transaction(async tx => { <p>“任何可能出错的事情都会出错。”我们的目标是防止出现问题,并在出现问题时减轻后果。</p> </blockquote> <p>界面是用户与系统通信的中介层,界面中的交互通常需要用户执行某些操作。不同的操作可能会导致不同的结果,其中可能有一些对于双方来说都非常重要甚至危险的操作。</p> -<p>所以经常需要提供额外的保护措施来“保护”用户执行一些危险甚至无法恢复的操作。<br>这里的“保护”并不是完全的阻止,否则这个操作也没有存在的必要。</p> +<p>所以经常需要提供额外的保护措施来“保护”用户执行一些危险甚至无法恢复的操作。<br> +这里的“保护”并不是完全的阻止,否则这个操作也没有存在的必要。</p> <blockquote> <p>“良好的错误消息很重要,但最好的设计首先会小心地防止问题发生。要么消除容易出错的情况,要么检查它们并在用户承诺操作之前向他们提供确认选项。”</p> </blockquote> -<h2 id="什么是危险行为?"><a href="#什么是危险行为?" class="headerlink" title="什么是危险行为?"></a>什么是危险行为?</h2><p>危险行为并不意味着要删除某些内容,具体的危险行为应该由系统的“领域”来定义,例如:</p> +<h2 id="什么是危险行为?"><a class="header-anchor" href="#什么是危险行为?">¶</a>什么是危险行为?</h2> +<p>危险行为并不意味着要删除某些内容,具体的危险行为应该由系统的“领域”来定义,例如:</p> <ul> <li>进行金融交易</li> <li>签署法律文件</li> @@ -4291,8 +4726,10 @@ await prisma.$transaction(async tx => { <li>授予某些用户权限</li> <li>…</li> </ul> -<h2 id="确认危险行为的方法"><a href="#确认危险行为的方法" class="headerlink" title="确认危险行为的方法"></a>确认危险行为的方法</h2><p>最常用的一种方法是要求用户明确确认他们的操作,这种方法也有很多实现上的细节,但无论从什么角度实现都有优劣:</p> -<h3 id="Modal-Dialog"><a href="#Modal-Dialog" class="headerlink" title="Modal Dialog"></a>Modal Dialog</h3><p>首先需要明确 Modal Dialog 和 Non-modal Dialog 的区别。</p> +<h2 id="确认危险行为的方法"><a class="header-anchor" href="#确认危险行为的方法">¶</a>确认危险行为的方法</h2> +<p>最常用的一种方法是要求用户明确确认他们的操作,这种方法也有很多实现上的细节,但无论从什么角度实现都有优劣:</p> +<h3 id="Modal-Dialog"><a class="header-anchor" href="#Modal-Dialog">¶</a>Modal Dialog</h3> +<p>首先需要明确 Modal Dialog 和 Non-modal Dialog 的区别。</p> <blockquote> <p>“Modal 是一种设计技术,它以一个独立的模式呈现内容,阻止用户与父视图交互,并需要明确的操作来退出。”</p> </blockquote> @@ -4309,7 +4746,8 @@ await prisma.$transaction(async tx => { </ol> <p>除此之外,还有更加严格的保护,例如在某些情况下,可以让用户输入某些内容来“解锁”操作,例如 Github 在删除仓库的时候需要输入仓库名称才能删除,这能让用户明确的知道自己在做什么,在删除哪个仓库。</p> <p>最后,根据 <a href="https://lawsofux.com/law-of-proximity/">临近法则</a> ,确认操作的按钮最好放在左侧。</p> -<h4 id="Danger-Zone"><a href="#Danger-Zone" class="headerlink" title="Danger Zone"></a>Danger Zone</h4><p>对于关键的操作,可以使用 Danger Zone,常见的实现方式是将这一类关键的操作单独放在某一个页面的同一处,例如页面的底部。如果操作比较多,可以考虑使用一个单独的页面存放。</p> +<h4 id="Danger-Zone"><a class="header-anchor" href="#Danger-Zone">¶</a>Danger Zone</h4> +<p>对于关键的操作,可以使用 Danger Zone,常见的实现方式是将这一类关键的操作单独放在某一个页面的同一处,例如页面的底部。如果操作比较多,可以考虑使用一个单独的页面存放。</p> <p>使用 Danger Zone 存放关键操作组件也有一些基本要素:</p> <ol> <li>使用红色或其他富含警示性颜色的警告图标或边框,在视觉上将 Danger Zone 与页面的其他部分区分开来。</li> @@ -4317,14 +4755,16 @@ await prisma.$transaction(async tx => { <li>对于一些非常关键且无法恢复的行为,可以要求用户进行额外的操作。例如要求用户重复输入密码或使用 2FA。</li> <li>只存放真正关键的操作。避免为了拥有一个 Danger Zone 而搞出一个 Danger Zone。</li> </ol> -<h3 id="Inline-Guard"><a href="#Inline-Guard" class="headerlink" title="Inline Guard"></a>Inline Guard</h3><p>这个方法解释起来挺简单,可以用在一些零碎的页面元素中,例如有一个删除一条消息的按钮,可以在用户单击这个按钮之后将其变为红色背景并修改按钮字体为 “确认删除”,用户再次点击就确认删除了。这用来防止误点击非常有用。</p> +<h3 id="Inline-Guard"><a class="header-anchor" href="#Inline-Guard">¶</a>Inline Guard</h3> +<p>这个方法解释起来挺简单,可以用在一些零碎的页面元素中,例如有一个删除一条消息的按钮,可以在用户单击这个按钮之后将其变为红色背景并修改按钮字体为 “确认删除”,用户再次点击就确认删除了。这用来防止误点击非常有用。</p> <p>但是也有一些细节需要注意:</p> <ol> <li>这种方法对于不那么危险的动作来说很方便,注意是“不那么危险”</li> <li>一个“不那么危险”的操作应该可以恢复,所以应该提供一个选项来撤消操作或将已删除的项目放到回收站之类的地方,这是确保用户安全操作的良好组合。</li> </ol> <p>Inline Guard 不能滥用,当用户非常频繁的遇到时会烦死,得权衡一下。</p> -<h3 id="其他方案"><a href="#其他方案" class="headerlink" title="其他方案"></a>其他方案</h3><p>还有一些方案这里简单说一下,一是 2FA,基本不用过多解释,二是双人验证甚至多人验证,就是用户发起的一个操作需要两个以上的人来验证才可以执行,例如 Github 的 Merge PR。</p> +<h3 id="其他方案"><a class="header-anchor" href="#其他方案">¶</a>其他方案</h3> +<p>还有一些方案这里简单说一下,一是 2FA,基本不用过多解释,二是双人验证甚至多人验证,就是用户发起的一个操作需要两个以上的人来验证才可以执行,例如 Github 的 Merge PR。</p> <p>当系统要求用户进行一些额外的操作时,应该明确其最初的目的,因为:</p> <ul> <li>认知惯性:一个人倾向于近乎惯性地决定,即使这些决定不适合当前情况。例如,绝大多数人不阅读用户协议。他们只是同意冗长的文本,因为从法律角度来看这是必要的。(是的我就是这样)</li> @@ -4332,10 +4772,13 @@ await prisma.$transaction(async tx => { <li>人类倾向于以更简单、更省力的方式思考和解决问题,而不是更复杂、更省力的方式,无论智力如何。所以许多用户只是点击“是”或“同意”而没有仔细阅读文本。</li> </ul> <p>所以在某些情况下,我们可以用一些更加优雅的方法:</p> -<h3 id="延迟"><a href="#延迟" class="headerlink" title="延迟"></a>延迟</h3><p>上面 Inline Guard 用在删除消息的场景下,也可以点击删除按钮直接删除,但同时显示一个倒计时的 Toast 并附带一个“撤销”的按钮来提醒用户。</p> -<h2 id="撤销"><a href="#撤销" class="headerlink" title="撤销"></a>撤销</h2><p>允许用户撤消刚刚执行的操作,从而提供一个安全网来减少因犯错误而产生的焦虑。<br>与 Modal Dialog 这种中断系统并要求用户确认的模式不同,撤消允许完成操作后在需要时选择撤消操作,从而提供更流畅的体验。</p> +<h3 id="延迟"><a class="header-anchor" href="#延迟">¶</a>延迟</h3> +<p>上面 Inline Guard 用在删除消息的场景下,也可以点击删除按钮直接删除,但同时显示一个倒计时的 Toast 并附带一个“撤销”的按钮来提醒用户。</p> +<h2 id="撤销"><a class="header-anchor" href="#撤销">¶</a>撤销</h2> +<p>允许用户撤消刚刚执行的操作,从而提供一个安全网来减少因犯错误而产生的焦虑。<br> +与 Modal Dialog 这种中断系统并要求用户确认的模式不同,撤消允许完成操作后在需要时选择撤消操作,从而提供更流畅的体验。</p> <p>它非常适合非破坏性、不可恢复的操作以及不会产生重大和直接后果的操作。</p> -<p>撤消选项与“软删除”的概念密切相关,“软删除” 的意思是:当用户通过 UI 删除某些内容时,_看起来它已被删除_,但在数据库中,我们保留数据但将其标记为已删除。数据不会丢失,这就是为什么可以使用撤消选项,因为我们实际上并没有删除任何内容,而是将其标记为已删除。</p> +<p>撤消选项与“软删除”的概念密切相关,“软删除” 的意思是:当用户通过 UI 删除某些内容时,<em>看起来它已被删除</em>,但在数据库中,我们保留数据但将其标记为已删除。数据不会丢失,这就是为什么可以使用撤消选项,因为我们实际上并没有删除任何内容,而是将其标记为已删除。</p> <p>晚安。</p> ]]></content> <tags> @@ -4347,18 +4790,20 @@ await prisma.$transaction(async tx => { <title>实时搜索中的防抖函数</title> <url>/2025/02/10/%E5%AE%9E%E6%97%B6%E6%90%9C%E7%B4%A2%E4%B8%AD%E7%9A%84%E9%98%B2%E6%8A%96%E5%87%BD%E6%95%B0/</url> <content><![CDATA[<p>在实现实时搜索功能时,通常会使用输入框的事件监听器来捕获用户的输入变化,并在输入变化时发送搜索请求。为了避免过多的请求导致服务器负担过重,通常会使用“防抖”(debounce)技术来控制请求的频率。</p> -<h3 id="实现步骤"><a href="#实现步骤" class="headerlink" title="实现步骤"></a>实现步骤</h3><ol> +<h3 id="实现步骤"><a class="header-anchor" href="#实现步骤">¶</a>实现步骤</h3> +<ol> <li>监听输入框的变化:使用<code>input</code>事件监听器来捕获用户的输入变化。</li> <li>防抖处理:使用防抖函数来限制请求的频率。防抖函数会在用户停止输入一段时间后才发送请求。</li> <li>发送请求:在防抖函数中调用搜索请求。</li> </ol> -<h3 id="防抖函数示例"><a href="#防抖函数示例" class="headerlink" title="防抖函数示例"></a>防抖函数示例</h3><p>以下是一个简单的防抖函数示例:</p> +<h3 id="防抖函数示例"><a class="header-anchor" href="#防抖函数示例">¶</a>防抖函数示例</h3> +<p>以下是一个简单的防抖函数示例:</p> <figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">debounce</span>(<span class="params">func, wait</span>) {</span><br><span class="line"> <span class="keyword">let</span> timeout;</span><br><span class="line"> <span class="keyword">return</span> <span class="keyword">function</span>(<span class="params">...args</span>) {</span><br><span class="line"> <span class="keyword">const</span> context = <span class="variable language_">this</span>;</span><br><span class="line"> <span class="built_in">clearTimeout</span>(timeout);</span><br><span class="line"> timeout = <span class="built_in">setTimeout</span>(<span class="function">() =></span> func.<span class="title function_">apply</span>(context, args), wait);</span><br><span class="line"> };</span><br><span class="line">}</span><br></pre></td></tr></table></figure> - -<h3 id="实现实时搜索"><a href="#实现实时搜索" class="headerlink" title="实现实时搜索"></a>实现实时搜索</h3><p>假设你有一个输入框用于搜索患者:</p> +<h3 id="实现实时搜索"><a class="header-anchor" href="#实现实时搜索">¶</a>实现实时搜索</h3> +<p>假设你有一个输入框用于搜索患者:</p> <figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line"><script></span><br><span class="line"> import { onMount } from 'svelte';</span><br><span class="line"> import { patientsStore } from '$lib/stores/patients.svelte';</span><br><span class="line"></span><br><span class="line"> let searchTerm = '';</span><br><span class="line"></span><br><span class="line"> // 防抖函数</span><br><span class="line"> function debounce(func, wait) {</span><br><span class="line"> let timeout;</span><br><span class="line"> return function(...args) {</span><br><span class="line"> const context = this;</span><br><span class="line"> clearTimeout(timeout);</span><br><span class="line"> timeout = setTimeout(() => func.apply(context, args), wait);</span><br><span class="line"> };</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> // 搜索函数</span><br><span class="line"> const searchPatients = debounce(async (term) => {</span><br><span class="line"> if (term) {</span><br><span class="line"> // 发送搜索请求</span><br><span class="line"> const response = await fetch(`/api/search-patients?query=${term}`);</span><br><span class="line"> const data = await response.json();</span><br><span class="line"> patientsStore.mbglPatients = data;</span><br><span class="line"> } else {</span><br><span class="line"> // 清空搜索结果或恢复默认数据</span><br><span class="line"> patientsStore.mbglPatients = [];</span><br><span class="line"> }</span><br><span class="line"> }, 300); // 300ms 的防抖时间</span><br><span class="line"></span><br><span class="line"> // 监听输入框变化</span><br><span class="line"> function handleInput(event) {</span><br><span class="line"> searchTerm = event.target.value;</span><br><span class="line"> searchPatients(searchTerm);</span><br><span class="line"> }</span><br><span class="line"></script></span><br><span class="line"></span><br><span class="line"><input type="text" placeholder="搜索患者..." on:input={handleInput} bind:value={searchTerm} /></span><br></pre></td></tr></table></figure> - -<h3 id="请求发送间隔"><a href="#请求发送间隔" class="headerlink" title="请求发送间隔"></a>请求发送间隔</h3><ul> +<h3 id="请求发送间隔"><a class="header-anchor" href="#请求发送间隔">¶</a>请求发送间隔</h3> +<ul> <li>防抖时间:通常设置为 300ms 到 500ms 之间。这个时间足够让用户完成输入并减少不必要的请求。</li> <li>考虑用户体验:防抖时间过短可能导致过多请求,过长则可能让用户感到延迟。300ms 是一个常用的折中值。</li> </ul> @@ -4372,8 +4817,10 @@ await prisma.$transaction(async tx => { <title>急诊与灾难医学--烧伤</title> <url>/2024/01/25/%E6%80%A5%E8%AF%8A%E4%B8%8E%E7%81%BE%E9%9A%BE%E5%8C%BB%E5%AD%A6-%E7%83%A7%E4%BC%A4/</url> <content><![CDATA[<p>烧伤,烫伤是一个很常见的急诊意外损伤,这里科普一下相关的知识。</p> -<h2 id="临床特点"><a href="#临床特点" class="headerlink" title="临床特点"></a>临床特点</h2><p>烧伤组织出现变性坏死,体液渗出引起组织水肿,变性,小面积的浅度烧伤,体液渗出有限,经过代偿之后不会影响身体的有效循环血量,大面积或者深度的烧伤,会因为大量渗出,休克,感染等病理变化导致并发脓毒症和多器官功能衰竭。</p> -<h3 id="烧伤面积判断"><a href="#烧伤面积判断" class="headerlink" title="烧伤面积判断"></a>烧伤面积判断</h3><p>首先我们要估算烧伤的面积,也就是判断皮肤烧伤区占人体表面积的百分比,最常用的是九分法和手掌法,前者用于大面积烧伤,后者用于小面积烧伤。</p> +<h2 id="临床特点"><a class="header-anchor" href="#临床特点">¶</a>临床特点</h2> +<p>烧伤组织出现变性坏死,体液渗出引起组织水肿,变性,小面积的浅度烧伤,体液渗出有限,经过代偿之后不会影响身体的有效循环血量,大面积或者深度的烧伤,会因为大量渗出,休克,感染等病理变化导致并发脓毒症和多器官功能衰竭。</p> +<h3 id="烧伤面积判断"><a class="header-anchor" href="#烧伤面积判断">¶</a>烧伤面积判断</h3> +<p>首先我们要估算烧伤的面积,也就是判断皮肤烧伤区占人体表面积的百分比,最常用的是九分法和手掌法,前者用于大面积烧伤,后者用于小面积烧伤。</p> <ul> <li>手掌法:病人的五个手指并拢后,手掌的面积估算为 1% 体表面积。</li> <li>九分法:</li> @@ -4386,7 +4833,8 @@ await prisma.$transaction(async tx => { <th>小儿各部位面积(%)</th> </tr> </thead> -<tbody><tr> +<tbody> +<tr> <td>头额</td> <td><code>9x1=9 (发部3,面部3,颈部3)</code></td> <td><code>9 + (12-年龄) </code></td> @@ -4406,8 +4854,10 @@ await prisma.$transaction(async tx => { <td><code>9x5+1=45 (双臀5, 双大腿21, 双小腿13, 双足7)</code></td> <td><code>46-(12-年龄)</code></td> </tr> -</tbody></table> -<h3 id="烧伤深度判断"><a href="#烧伤深度判断" class="headerlink" title="烧伤深度判断"></a>烧伤深度判断</h3><p>三度四分法:</p> +</tbody> +</table> +<h3 id="烧伤深度判断"><a class="header-anchor" href="#烧伤深度判断">¶</a>烧伤深度判断</h3> +<p>三度四分法:</p> <ul> <li>I 度:仅伤及表皮浅层</li> <li>浅 II 度:伤及表皮的生发层与真皮乳头层</li> @@ -4424,7 +4874,8 @@ await prisma.$transaction(async tx => { <th>预后</th> </tr> </thead> -<tbody><tr> +<tbody> +<tr> <td>I</td> <td>粉红或红色</td> <td>干燥</td> @@ -4452,7 +4903,8 @@ await prisma.$transaction(async tx => { <td>无感觉</td> <td>需切痂皮,植皮,皮瓣移植或截肢</td> </tr> -</tbody></table> +</tbody> +</table> <p>根据以上的参考,可以把伤情分为四类:</p> <ol> <li>轻度烧伤:总面积 9% 以下的 II 度烧伤</li> @@ -4463,24 +4915,32 @@ await prisma.$transaction(async tx => { <hr> <p><strong>根据烧伤病史和临床表现,要注意包括对烧伤严重程度的判断,烧伤原因的鉴别,需要排除电和化学烧伤</strong></p> <hr> -<h2 id="急诊处理"><a href="#急诊处理" class="headerlink" title="急诊处理"></a>急诊处理</h2><h3 id="现场急救"><a href="#现场急救" class="headerlink" title="现场急救"></a>现场急救</h3><ol> +<h2 id="急诊处理"><a class="header-anchor" href="#急诊处理">¶</a>急诊处理</h2> +<h3 id="现场急救"><a class="header-anchor" href="#现场急救">¶</a>现场急救</h3> +<ol> <li>迅速脱离热源,褪去衣物,不可粗暴剥脱。在现场可用干净敷料或布织物保护伤处,立即送医</li> -<li>初步判断伤情,如有大出血,窒息,开放性气胸,严重中毒,立即组织抢救<blockquote> -<p>烧伤常伴呼吸道受烟雾,热力灼伤<br>切记注意有无呼吸道吸入性损伤,保持呼吸通畅,<strong>必要时切开气管</strong><br>出现心脏骤停,确认环境安全后,迅速心肺复苏</p> +<li>初步判断伤情,如有大出血,窒息,开放性气胸,严重中毒,立即组织抢救 +<blockquote> +<p>烧伤常伴呼吸道受烟雾,热力灼伤<br> +切记注意有无呼吸道吸入性损伤,保持呼吸通畅,<strong>必要时切开气管</strong><br> +出现心脏骤停,确认环境安全后,迅速心肺复苏</p> </blockquote> </li> <li>轻度烧伤,特别是四肢烧伤,立即用冷水连续冲洗或浸泡</li> <li>大面积烧伤,立即建立静脉通道,予以补液,抗休克治疗</li> <li>转运伤员就近原则,严重烧伤早期,<strong>切忌长途转运</strong></li> </ol> -<h3 id="急诊治疗"><a href="#急诊治疗" class="headerlink" title="急诊治疗"></a>急诊治疗</h3><h4 id="轻度烧伤"><a href="#轻度烧伤" class="headerlink" title="轻度烧伤"></a>轻度烧伤</h4><blockquote> +<h3 id="急诊治疗"><a class="header-anchor" href="#急诊治疗">¶</a>急诊治疗</h3> +<h4 id="轻度烧伤"><a class="header-anchor" href="#轻度烧伤">¶</a>轻度烧伤</h4> +<blockquote> <p>处理创面,<strong>小心</strong> 剔净创面周围毛发,清洁健康皮肤,去除异物。</p> </blockquote> <ul> <li>I 度创面无需处理,外敷清凉药物即可</li> <li>浅 II 度,如果水疱完整,不要动它,如果水疱很大,用消毒空针去抽水疱液,然后消毒包扎,如果水疱已经撕破,用无菌纱布,油性敷料包扎。创面无感染无需经常换药,面颈部和会阴部烧伤可以予以暴露,关节部位 II~III 度必须用夹板固定关节,按需用止痛镇静药物,酌情使用破伤风抗毒素。</li> </ul> -<h1 id="中度及以上烧伤立刻运送至有烧伤专科的医院"><a href="#中度及以上烧伤立刻运送至有烧伤专科的医院" class="headerlink" title="中度及以上烧伤立刻运送至有烧伤专科的医院"></a>中度及以上烧伤立刻运送至有烧伤专科的医院</h1><p>处理要点:</p> +<h1>中度及以上烧伤立刻运送至有烧伤专科的医院</h1> +<p>处理要点:</p> <ol> <li>吸氧,呼吸支持,建立输液通道,留置尿管,观察每小时尿量,比重,pH,有无血红蛋白尿,肌红蛋白尿。</li> <li>估算烧伤面积,深度</li> @@ -4492,7 +4952,8 @@ await prisma.$transaction(async tx => { <li>肠内肠外营养支持,尽量肠内营养</li> <li>减少瘢痕,挛缩,进行功能康复</li> </ol> -<h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><ul> +<h2 id="参考"><a class="header-anchor" href="#参考">¶</a>参考</h2> +<ul> <li>《外科护理学【第六版】》</li> <li>《烧伤外科学分册》</li> <li>《急诊与灾难医学【第三版】》</li> @@ -4505,21 +4966,27 @@ await prisma.$transaction(async tx => { <entry> <title>慢性肺源性心脏病</title> <url>/2024/01/23/%E6%85%A2%E6%80%A7%E8%82%BA%E6%BA%90%E6%80%A7%E5%BF%83%E8%84%8F%E7%97%85/</url> - <content><![CDATA[<p>肺源性心脏病(cor pulmonale)简称肺心病, 指由于支气管-肺组织, 胸廓或肺血管病变引起肺血管阻力增加, 产生肺动脉高压,继而右心室结构和/或功能改变的疾病.<br>根据起病缓急和病程长短, 可分为急性肺心病和慢性肺心病两类, 急性肺心病常见于急性大面积肺栓塞,这里主要讲慢性肺心病.</p> + <content><![CDATA[<p>肺源性心脏病(cor pulmonale)简称肺心病, 指由于支气管-肺组织, 胸廓或肺血管病变引起肺血管阻力增加, 产生肺动脉高压,继而右心室结构和/或功能改变的疾病.<br> +根据起病缓急和病程长短, 可分为急性肺心病和慢性肺心病两类, 急性肺心病常见于急性大面积肺栓塞,这里主要讲慢性肺心病.</p> <p>慢性肺心病是常见的呼吸系统疾病.患病率存在地区差异, 北方地区高于南方地区,农村高于城市.患病率随年龄增高而增加, 吸烟者比不吸烟者患病率明显增多, 男女无明显差异.</p> <p>冬春季节和气候骤变时, 易出现急性发作.</p> -<h2 id="病因与发病机制"><a href="#病因与发病机制" class="headerlink" title="病因与发病机制"></a>病因与发病机制</h2><h3 id="病因"><a href="#病因" class="headerlink" title="病因"></a>病因</h3><ol> +<h2 id="病因与发病机制"><a class="header-anchor" href="#病因与发病机制">¶</a>病因与发病机制</h2> +<h3 id="病因"><a class="header-anchor" href="#病因">¶</a>病因</h3> +<ol> <li>支气管, 肺疾病: 最多见为COPD, 占80%~90%, 其次为哮喘, 支气管扩张症, 肺结核, 间质性肺疾病等.</li> <li>胸廓运动障碍性疾病: 较少见, 严重胸廓或脊椎畸形以及神经肌肉疾患均可引起胸廓活动受限, 肺受压, 支气管扭曲或变形, 气道引流不畅,肺部反复感染,并发肺气肿或纤维化,最终引起慢性肺心病.</li> <li>肺血管疾病: 特发性或慢性栓塞性肺动脉高压, 肺小动脉炎均可起肺血管阻力增加, 肺动脉压升高和右心室负荷加重,发展为慢性肺心病.</li> <li>其他: 原发性肺泡通气不足及先天性口咽畸形, 睡眠呼吸暂停低通气综合征等均可产生低氧血症, 引起肺血管收缩, 导致肺动脉高压, 发展为慢性肺心病.</li> </ol> -<h3 id="发病机制"><a href="#发病机制" class="headerlink" title="发病机制"></a>发病机制</h3><blockquote> +<h3 id="发病机制"><a class="header-anchor" href="#发病机制">¶</a>发病机制</h3> +<blockquote> <p>肺动脉高压的形成: 不同疾病所致肺动脉高压的机制不完全一样, 这里记录低氧性肺动脉高压, 尤其COPD所致肺动脉高压的机制.</p> </blockquote> <ol> -<li>肺血管阻力增加的功能性因素: 肺血管收缩在低氧性肺动脉高压的发生中起着关键作用.缺氧, 高碳酸血症和呼吸性酸中毒导致肺血管收缩, 痉挛, 其中缺氧是肺动脉高压形成最重要的因素.缺氧时收缩血管的活性物质增多,使肺血管收缩, 血管阻力增加.缺氧使肺血管平滑肌细胞膜对 <code>Ca2+</code> 的通透性增加, 直接使肺血管平滑肌收缩.另外, 高碳酸血症时,『产生增多,使血管对缺氧的敏感<br>性增强, 致肺动脉压增高.</li> -<li>肺血管阻力增加的解剖学因素: 解剖学因素系指肺血管解剖结构的变化, 形成肺循环血流动力学障碍.主要原因有:<ol> +<li>肺血管阻力增加的功能性因素: 肺血管收缩在低氧性肺动脉高压的发生中起着关键作用.缺氧, 高碳酸血症和呼吸性酸中毒导致肺血管收缩, 痉挛, 其中缺氧是肺动脉高压形成最重要的因素.缺氧时收缩血管的活性物质增多,使肺血管收缩, 血管阻力增加.缺氧使肺血管平滑肌细胞膜对 <code>Ca2+</code> 的通透性增加, 直接使肺血管平滑肌收缩.另外, 高碳酸血症时,『产生增多,使血管对缺氧的敏感<br> +性增强, 致肺动脉压增高.</li> +<li>肺血管阻力增加的解剖学因素: 解剖学因素系指肺血管解剖结构的变化, 形成肺循环血流动力学障碍.主要原因有: +<ol> <li>长期反复发作的COPD及支气管周围炎,可累及邻近肺小动脉, 引起血管炎, 使肺血管阻力增加, 产生肺动脉高压.</li> <li>肺气肿导致肺泡内压增高, 压迫肺泡毛细血管, 造成管腔狭窄或闭塞.肺泡壁破裂造成毛细血管网的毁损, 当肺泡毛细血管床减损超过70%时肺循环阻力增大.</li> <li>肺血管重构:慢性缺氧使肺血管收缩, 管壁张力增高.缺氧时肺内产生多种生长因子,可直接刺激管壁平滑肌细胞, 内膜弹力纤维及胶原纤维增生.</li> @@ -4530,43 +4997,55 @@ await prisma.$transaction(async tx => { <li>心脏病变和心力衰竭:肺循环阻力增加导致肺动脉高压, 右心发挥代偿作用, 以克服肺动脉压升高的阻力而发生右心室肥厚.随着病情进展, 肺动脉压持续升高, 右心失代偿而致右心衰竭.</li> <li>其他重要器官的损害:缺氧和高碳酸血症可导致重要器官如脑, 肝, 肾, 胃肠及内分泌系统, 血液系统等发生病理改变, 引起多脏器的功能损害.</li> </ol> -<h2 id="临床表现"><a href="#临床表现" class="headerlink" title="临床表现"></a>临床表现</h2><h1 id="肺-心功能代偿期"><a href="#肺-心功能代偿期" class="headerlink" title="肺, 心功能代偿期"></a>肺, 心功能代偿期</h1><ol> +<h2 id="临床表现"><a class="header-anchor" href="#临床表现">¶</a>临床表现</h2> +<h1>肺, 心功能代偿期</h1> +<ol> <li>症状:C0PD病人可有咳嗽, 咳痰, 气促, 活动后可有心悸, 呼吸困难, 乏力和劳动耐力下降,少有胸痛或咯血.</li> <li>体征:原发肺脏疾病体征, 可有不同程度的发维和肺气肿体征,可见肺动脉高压和右室扩大的体征.</li> </ol> -<h2 id="肺-心功能失代偿期"><a href="#肺-心功能失代偿期" class="headerlink" title="肺, 心功能失代偿期"></a>肺, 心功能失代偿期</h2><ol> -<li>呼吸衰竭<ul> +<h2 id="肺-心功能失代偿期"><a class="header-anchor" href="#肺-心功能失代偿期">¶</a>肺, 心功能失代偿期</h2> +<ol> +<li>呼吸衰竭 +<ul> <li>症状:呼吸困难加重, 夜间为甚, 常有头痛, 失眠, 食欲下降, 白天嗜睡, 甚至出现表情淡漠, 神志恍惚, 澹妄等肺性脑病的表现.</li> <li>体征:明显发维, 球结膜充血, 水肿, 严重时可有视网膜血管, 视盘水肿等颅内压升高的表现.腱反射减弱或消失, 出现病理反射.因高碳酸血症可出现周围血管扩张的表现, 如皮肤潮红, 多汗.</li> </ul> </li> -<li>右心衰竭<ul> +<li>右心衰竭 +<ul> <li>症状:明显气促, 心悸, 食欲缺乏, 腹胀, 恶心等.</li> <li>体征:发绡明显, 颈静脉怒张, 心率增快, 可出现心律失常, 剑突下可闻及收缩期杂音, 甚至出现舒张期杂音.肝大并有压痛,肝颈静脉回流征阳性, 下肢水肿,重者可有腹水.</li> </ul> </li> <li>并发症: 肺性脑病, 电解质及酸碱平衡紊乱, 心律失常, 休克, 消化道出血和弥散性血管内凝血等.</li> </ol> -<h2 id="实验室及其他检查"><a href="#实验室及其他检查" class="headerlink" title="实验室及其他检查"></a>实验室及其他检查</h2><ol> +<h2 id="实验室及其他检查"><a class="header-anchor" href="#实验室及其他检查">¶</a>实验室及其他检查</h2> +<ol> <li>胸部X线检查: 除肺, 胸基础疾病及急性肺部感染的特征外, 尚有肺动脉高压征象.</li> -<li>心电图检查: 心电图对慢性肺心病的诊断阳性率为60. 1%〜88. 2%.主要表现有电轴右偏,<br>肺性P波.</li> +<li>心电图检查: 心电图对慢性肺心病的诊断阳性率为60. 1%〜88. 2%.主要表现有电轴右偏,<br> +肺性P波.</li> <li>超声心动图检查: 超声心动图诊断慢性肺心病的阳性率为60.6%〜87.0%.</li> <li>动脉血气分析: 可出现低氧血症,甚至呼吸衰竭或合并高碳酸血症.</li> <li>血液检查: 红细胞及血红蛋白可升高, 全血及血浆黏度可增加, 心功能不全时可伴有肾功能或肝功能异常.</li> <li>其他: 早期或缓解期病人可行肺功能检查.痰细菌学检查可指导抗生素的选用.</li> </ol> -<h2 id="治疗要点"><a href="#治疗要点" class="headerlink" title="治疗要点"></a>治疗要点</h2><h3 id="肺-心功能代偿期-1"><a href="#肺-心功能代偿期-1" class="headerlink" title="肺, 心功能代偿期"></a>肺, 心功能代偿期</h3><p>可采用综合治疗措施, 延缓基础疾病进展, 增强病人的免疫功能,预防感染,减少或避免急性加重, 加强康复锻炼和营养,必要时长期家庭氧疗或家庭无创呼吸机治疗等.</p> -<h3 id="肺-心功能失代偿期-1"><a href="#肺-心功能失代偿期-1" class="headerlink" title="肺, 心功能失代偿期"></a>肺, 心功能失代偿期</h3><p>治疗原则为积极控制感染, 保持呼吸道通畅,改善呼吸功能, 纠正缺氧和二氧化碳潴留, 控制呼吸衰竭和心力衰竭, 处理并发症.</p> +<h2 id="治疗要点"><a class="header-anchor" href="#治疗要点">¶</a>治疗要点</h2> +<h3 id="肺-心功能代偿期"><a class="header-anchor" href="#肺-心功能代偿期">¶</a>肺, 心功能代偿期</h3> +<p>可采用综合治疗措施, 延缓基础疾病进展, 增强病人的免疫功能,预防感染,减少或避免急性加重, 加强康复锻炼和营养,必要时长期家庭氧疗或家庭无创呼吸机治疗等.</p> +<h3 id="肺-心功能失代偿期-v2"><a class="header-anchor" href="#肺-心功能失代偿期-v2">¶</a>肺, 心功能失代偿期</h3> +<p>治疗原则为积极控制感染, 保持呼吸道通畅,改善呼吸功能, 纠正缺氧和二氧化碳潴留, 控制呼吸衰竭和心力衰竭, 处理并发症.</p> <ol> <li>控制感染:参考痰培养及药敏试验选择抗生素.没有培养结果时, 根据感染的环境及痰涂片结果选用抗生素.常用青霉素类, 氨基糖甘类, 喳诺酮类或头抱菌素类药物.注意继发真菌感染的可能.</li> <li>控制呼吸衰竭:使用支气管舒张药和祛痰药, 吸痰, 通畅呼吸道, 改善通气功能.合理氧疗.需要时给予无创正压通气或气管插管有创正压通气治疗.详见本章第十四节“呼吸衰竭”的治疗.</li> -<li>控制心力衰竭:慢性肺心病病人一般经积极控制感染, 改善呼吸功能, 纠正缺氧和二氧化碳潴留后, 心力衰竭便能得到改善,病人尿量增多, 水肿消退, 不需常规使用利尿药和正性肌力药.但病情较重或对上述治疗无效的病人, 可适当选用利尿药, 正性肌力药或扩血管药物.<ol> +<li>控制心力衰竭:慢性肺心病病人一般经积极控制感染, 改善呼吸功能, 纠正缺氧和二氧化碳潴留后, 心力衰竭便能得到改善,病人尿量增多, 水肿消退, 不需常规使用利尿药和正性肌力药.但病情较重或对上述治疗无效的病人, 可适当选用利尿药, 正性肌力药或扩血管药物. +<ol> <li>利尿药:具有消除水肿, 减少血容量, 减轻右心前负荷的作用.原则上选用作用温和的利尿药, 联合保钾利尿药,宜短期, 小剂量使用.如氢氯廛嗪25mg,每天1〜3次;联用螺内酯20〜40mg,每天1〜2次.应用利尿药易出现低钾, 低氯性碱中毒, 痰液黏稠不易排痰和血液浓缩,应注意预防.</li> -<li>正性肌力药:由于慢性缺氧和感染,慢性肺心病病人对洋地黄类药物耐受性低, 容易中毒, 出现心律失常.原则上选用作用快, 排泄快的洋地黄类药物, 小剂量(常规剂量的1/2或2/3量)静脉给药.用药前注意纠正缺氧, 防治低钾血症, 以免发生药物毒性反应.</li> +<li>正性肌力药:由于慢性缺氧和感染,慢性肺心病病人对洋地黄类药物耐受性低, 容易中毒, 出现心律失常.原则上选用作用快, 排泄快的洋地黄类药物, 小剂量(常规剂量的1/2或2/3量)静脉给药.用药前注意纠正缺氧, 防治低钾血症, 以免发生药物毒性反应.</li> </ol> </li> </ol> -<h2 id="健康指导"><a href="#健康指导" class="headerlink" title="健康指导"></a>健康指导</h2><ol> +<h2 id="健康指导"><a class="header-anchor" href="#健康指导">¶</a>健康指导</h2> +<ol> <li>疾病预防指导: 由于慢性肺心病是各种原发肺胸疾病晚期的并发症, 应对高危人群进行宣传教育, 劝导戒烟, 积极防治COPD等慢性支气管肺疾病, 以降低发病率.</li> <li>疾病知识指导: 使病人和家属了解疾病发生, 发展过程, 减少反复发作的次数.积极防治原发病, 避免和防治各种可能导致病情急性加重的诱因, 坚持家庭氧疗等.加强饮食营养, 以保证机体康复的需要.病情缓解期应根据肺, 心功能及体力情况进行适当的体育锻炼和呼吸功能锻炼如散步, 气功, 太极拳, 腹式呼吸, 缩唇呼吸等, 改善呼吸功能,提高机体免疫功能.</li> <li>病情监测指导: 告知病人及家属病情变化的征象, 如体温升高, 呼吸困难加重, 咳嗽剧烈, 咳痰不畅, 尿量减少, 水肿明显或发现病人神志淡漠, 嗜睡, 躁动, 口唇发纳加重等,均提示病情变化或加重,需及时就诊.</li> @@ -4579,13 +5058,16 @@ await prisma.$transaction(async tx => { <entry> <title>替米沙坦</title> <url>/2023/03/13/%E6%9B%BF%E7%B1%B3%E6%B2%99%E5%9D%A6/</url> - <content><![CDATA[<h2 id="名称"><a href="#名称" class="headerlink" title="名称"></a>名称</h2><p>中文名称: 替米沙坦</p> + <content><![CDATA[<h2 id="名称"><a class="header-anchor" href="#名称">¶</a>名称</h2> +<p>中文名称: 替米沙坦</p> <p>中文别名: 4-{[2-正丙基-4-甲基-6-(1-甲基苯并咪唑-2-基)苯并咪唑-1-基]甲基}联苯基-2-羧酸</p> <p>英文名称: Telmisartan</p> -<p>英文别名: 4’[(1,4’-Dimethyl-2’-propyl[2,6’-bi-1H-benzimidazol]-1’-yl)methyl][1,1’-biphenyl]-2-carboxylic acid </p> -<h2 id="概要"><a href="#概要" class="headerlink" title="概要"></a>概要</h2><p>替米沙坦是一种新型的降血压药物,是一种特异性血管紧张素Ⅱ受体(ATⅠ型)拮抗剂。替米沙坦替代血管紧张素Ⅱ受体与ATⅠ受体亚型(已知的血管紧张素Ⅱ作用位点)高亲和性结合。替米沙坦在ATⅠ受体位点无任何部位激动剂效应,替米沙坦选择性与ATⅠ受体结合,该结合作用持久。替米沙坦对其他受体(包括AT2和其它特征更少的AT受体)无亲和力。上述其它受体的功能尚未可知,由于替米沙坦导致血管紧张素Ⅱ水平增高,从而可能引起的受体过度刺激效应亦不可知。替米沙坦不抑制人体血浆肾素,亦不阻断离子通道。替米沙坦不抑制血管紧张素转换酶Ⅱ,该酶亦可降解缓激肽作用增强导致的不良反应。在人体给予80mg替米沙坦几乎可完全抑制血管紧张素Ⅱ引起的血压升高。抑制效应持续24小时,在48小时仍可测到。首剂替米沙坦后3小时内降压效应逐渐明显。在治疗开始后4周可获得最大降压效果,并可在长期治疗中维持。替米沙坦治疗如突然中断,数天后血压逐渐恢复到治疗前水平,而不出现反弹性高血压。在直接比较两种高血压药物的临床试验研究中,替米沙坦治疗组的患者干咳发生率显著低于血管紧张素转换酶抑制剂治疗组。 </p> +<p>英文别名: 4’[(1,4’-Dimethyl-2’-propyl[2,6’-bi-1H-benzimidazol]-1’-yl)methyl][1,1’-biphenyl]-2-carboxylic acid</p> +<h2 id="概要"><a class="header-anchor" href="#概要">¶</a>概要</h2> +<p>替米沙坦是一种新型的降血压药物,是一种特异性血管紧张素Ⅱ受体(ATⅠ型)拮抗剂。替米沙坦替代血管紧张素Ⅱ受体与ATⅠ受体亚型(已知的血管紧张素Ⅱ作用位点)高亲和性结合。替米沙坦在ATⅠ受体位点无任何部位激动剂效应,替米沙坦选择性与ATⅠ受体结合,该结合作用持久。替米沙坦对其他受体(包括AT2和其它特征更少的AT受体)无亲和力。上述其它受体的功能尚未可知,由于替米沙坦导致血管紧张素Ⅱ水平增高,从而可能引起的受体过度刺激效应亦不可知。替米沙坦不抑制人体血浆肾素,亦不阻断离子通道。替米沙坦不抑制血管紧张素转换酶Ⅱ,该酶亦可降解缓激肽作用增强导致的不良反应。在人体给予80mg替米沙坦几乎可完全抑制血管紧张素Ⅱ引起的血压升高。抑制效应持续24小时,在48小时仍可测到。首剂替米沙坦后3小时内降压效应逐渐明显。在治疗开始后4周可获得最大降压效果,并可在长期治疗中维持。替米沙坦治疗如突然中断,数天后血压逐渐恢复到治疗前水平,而不出现反弹性高血压。在直接比较两种高血压药物的临床试验研究中,替米沙坦治疗组的患者干咳发生率显著低于血管紧张素转换酶抑制剂治疗组。</p> <p>替米沙坦降压幅度大,部分患者可能会出现低血压,这个倒是挺尴尬的。</p> -<h2 id="要点"><a href="#要点" class="headerlink" title="要点"></a>要点</h2><p>1 药代动力学显示:作用迅速(0.3h),持续时间长 (35.4h),降压时对心率的影响小</p> +<h2 id="要点"><a class="header-anchor" href="#要点">¶</a>要点</h2> +<p>1 药代动力学显示:作用迅速(0.3h),持续时间长 (35.4h),降压时对心率的影响小</p> <p>2 同依那普利比较:降压效果优于依那普利,两者同利尿剂合用,效果 仍为替米沙坦好,且咳嗽发生率少</p> <p>3 同赖诺普利比较:降压(收缩压和舒张压)效果更为明显,咳嗽发生率替米沙坦组(16%)明显低于赖诺普利组(60%)</p> <p>4 同阿替洛尔比较:降压效果相当,副作用(阳痿和疲劳)发生率低</p> @@ -4594,13 +5076,23 @@ await prisma.$transaction(async tx => { <p>具有受体作用的专一性</p> <p>抗高血压作用显著</p> <p>具有良好的利尿作用</p> -<p>能改善心肌狭窄障碍 </p> -<h2 id="注意"><a href="#注意" class="headerlink" title="注意"></a>注意</h2><p>成人用药:一次mg—80mg,一日一次。服用时间不受饮食影响。 轻或中度肾功能不良的病人,以及老人服用本品不需调整剂量。轻或中度肝功能不全的病人,本品用量不应超过40mg/日。对于儿童:本品的安全性及有效性数据尚未建立。 腹泻和血管性水肿。大多为轻微的和暂时的,一般不需停止治疗。其发生与剂量无相关性。</p> -<p>注意:<br>1.本品使用过量时若发生症状性低血压应进行支持性治疗,本品不能通过血液透析清除。<br>2.本品可能会增加抗高血压药物的降压作用。<br>3.与某些药物合用时应监测血清锂水平。<br>4.轻至中度肾功能损伤患者不需调整本品剂量<br> > 替米沙坦主要通过肝脏代谢,胆汁排泄,胆汁淤积、胆道梗阻或严重肝功能不全患者不应使用替米沙坦,用药期间定期检查肝功能,肾功能不全的患者用药期间要密切监测血钾水平。</p> -<p>5.孕妇及哺辱期妇女禁用本品。<br>6.儿童患者使用本品的安全性尚未确立,儿童慎用。 </p> -<p>特别注意的是!<br>1.对患有胆汁梗阻性疾病和严重肝肾功能不全者禁用。<br>2.孕妇及哺辱期妇女禁用。 </p> -<h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><ul> -<li><a href="https://www.yixue.com/%E6%9B%BF%E7%B1%B3%E6%B2%99%E5%9D%A6">https://www.yixue.com/%E6%9B%BF%E7%B1%B3%E6%B2%99%E5%9D%A6</a></li> +<p>能改善心肌狭窄障碍</p> +<h2 id="注意"><a class="header-anchor" href="#注意">¶</a>注意</h2> +<p>成人用药:一次mg—80mg,一日一次。服用时间不受饮食影响。 轻或中度肾功能不良的病人,以及老人服用本品不需调整剂量。轻或中度肝功能不全的病人,本品用量不应超过40mg/日。对于儿童:本品的安全性及有效性数据尚未建立。 腹泻和血管性水肿。大多为轻微的和暂时的,一般不需停止治疗。其发生与剂量无相关性。</p> +<p>注意:<br> +1.本品使用过量时若发生症状性低血压应进行支持性治疗,本品不能通过血液透析清除。<br> +2.本品可能会增加抗高血压药物的降压作用。<br> +3.与某些药物合用时应监测血清锂水平。<br> +4.轻至中度肾功能损伤患者不需调整本品剂量<br> +> 替米沙坦主要通过肝脏代谢,胆汁排泄,胆汁淤积、胆道梗阻或严重肝功能不全患者不应使用替米沙坦,用药期间定期检查肝功能,肾功能不全的患者用药期间要密切监测血钾水平。</p> +<p>5.孕妇及哺辱期妇女禁用本品。<br> +6.儿童患者使用本品的安全性尚未确立,儿童慎用。</p> +<p>特别注意的是!<br> +1.对患有胆汁梗阻性疾病和严重肝肾功能不全者禁用。<br> +2.孕妇及哺辱期妇女禁用。</p> +<h2 id="参考"><a class="header-anchor" href="#参考">¶</a>参考</h2> +<ul> +<li><a href="https://www.yixue.com/%E6%9B%BF%E7%B1%B3%E6%B2%99%E5%9D%A6">https://www.yixue.com/替米沙坦</a></li> </ul> ]]></content> <tags> @@ -4618,10 +5110,15 @@ await prisma.$transaction(async tx => { <li>呼吸困难,就像有人捂住你的口鼻,有点窒息的感觉。</li> </ol> <p>通俗来讲造成这种感觉的原因是肺泡破裂,肺漏气了。然后气体在胸腔里聚集就压缩了肺。</p> -<p><img src="/img/%E5%8C%BB%E5%AD%A6/%E6%B0%94%E8%83%B8/%E6%B0%94%E8%83%B82.jpeg" alt="气胸2.jpeg"><br>图中是一位右侧气胸患者(图中右面)的电脑断层扫描影像。在胸腔的边缘有着引流管,而图中黑色一片就是邻近于肺膜间(黑)和肋骨(白)的内腔。心脏则在图中央。医学专科胸腔医学、胸腔外科学症状胸痛、呼吸困难、疲劳常见始发于突发性肇因未知、创伤风险因子慢性阻塞性肺病(COPD)、结核病、抽烟诊断方法胸部X光、超声波、电脑断层扫描相似疾病或共病肺部大疱、血胸预防禁烟或戒烟治疗保守治疗、空针穿刺、胸管置放、肋膜黏连术盛行率约每10万人中20例外伤性气胸。</p> -<h2 id="临床表现"><a href="#临床表现" class="headerlink" title="临床表现"></a>临床表现</h2><p>在医学上的临床表现中,气胸具有如下症状:<br>患者常有持重物、屏气、剧烈运动等诱发因素,但也有在睡眠中发生气胸者,病人突感一侧胸痛、气急、憋气,可有咳嗽、但痰少,小量闭合性气胸先有气急,但数小时后逐渐平稳,X线也不一定能显示肺压缩。若积气量较大者或者原来已有广泛肺部疾患,病人常不能平卧。如果侧卧,则被迫使气胸患侧在上,以减轻气急。病人呼吸困难程度与积气量的多寡以及原来肺内病变范围有关。当有胸膜粘连和肺功能减损时,即使小量局限性气胸也可能明显胸痛和气急。</p> -<h2 id="初步诊断方式"><a href="#初步诊断方式" class="headerlink" title="初步诊断方式"></a>初步诊断方式</h2><p>突发一侧胸痛,伴有呼吸困难并有气胸体征,即可作出初步诊断。X线显示气胸征是确诊依据。在无条件或病情危重不允许作X线检查时,可在患侧胸腔积气体征最明确处试穿,抽气测压,若为正压且抽出气体,说明有气胸存在,即应抽出气体以缓解症状,并观察抽气后胸腔内压力的变化以判断气胸类型。在原有严重哮喘或肺气肿基础上并发气胸时,气急、胸闷等症状有时不易觉察,要与原先症状仔细比较。 </p> -<h2 id="类似病症需要区别开来"><a href="#类似病症需要区别开来" class="headerlink" title="类似病症需要区别开来"></a>类似病症需要区别开来</h2><ol> +<p><img src="/img/%E5%8C%BB%E5%AD%A6/%E6%B0%94%E8%83%B8/%E6%B0%94%E8%83%B82.jpeg" alt="气胸2.jpeg"><br> +图中是一位右侧气胸患者(图中右面)的电脑断层扫描影像。在胸腔的边缘有着引流管,而图中黑色一片就是邻近于肺膜间(黑)和肋骨(白)的内腔。心脏则在图中央。医学专科胸腔医学、胸腔外科学症状胸痛、呼吸困难、疲劳常见始发于突发性肇因未知、创伤风险因子慢性阻塞性肺病(COPD)、结核病、抽烟诊断方法胸部X光、超声波、电脑断层扫描相似疾病或共病肺部大疱、血胸预防禁烟或戒烟治疗保守治疗、空针穿刺、胸管置放、肋膜黏连术盛行率约每10万人中20例外伤性气胸。</p> +<h2 id="临床表现"><a class="header-anchor" href="#临床表现">¶</a>临床表现</h2> +<p>在医学上的临床表现中,气胸具有如下症状:<br> +患者常有持重物、屏气、剧烈运动等诱发因素,但也有在睡眠中发生气胸者,病人突感一侧胸痛、气急、憋气,可有咳嗽、但痰少,小量闭合性气胸先有气急,但数小时后逐渐平稳,X线也不一定能显示肺压缩。若积气量较大者或者原来已有广泛肺部疾患,病人常不能平卧。如果侧卧,则被迫使气胸患侧在上,以减轻气急。病人呼吸困难程度与积气量的多寡以及原来肺内病变范围有关。当有胸膜粘连和肺功能减损时,即使小量局限性气胸也可能明显胸痛和气急。</p> +<h2 id="初步诊断方式"><a class="header-anchor" href="#初步诊断方式">¶</a>初步诊断方式</h2> +<p>突发一侧胸痛,伴有呼吸困难并有气胸体征,即可作出初步诊断。X线显示气胸征是确诊依据。在无条件或病情危重不允许作X线检查时,可在患侧胸腔积气体征最明确处试穿,抽气测压,若为正压且抽出气体,说明有气胸存在,即应抽出气体以缓解症状,并观察抽气后胸腔内压力的变化以判断气胸类型。在原有严重哮喘或肺气肿基础上并发气胸时,气急、胸闷等症状有时不易觉察,要与原先症状仔细比较。</p> +<h2 id="类似病症需要区别开来"><a class="header-anchor" href="#类似病症需要区别开来">¶</a>类似病症需要区别开来</h2> +<ol> <li>支气管哮喘和阻塞性肺气肿: 有气急和呼吸困难,体征亦与自发性气胸相似,但肺气肿呼吸困难是长期缓慢加重的,支气管哮喘病人有多年哮喘反复发作史。当哮喘和肺气肿病人呼吸困难突然加重且有胸痛,应考虑并发气胸的可能,X线检查可以作出鉴别。</li> <li>急性心肌梗塞: 病人亦有急起胸痛、胸闷、甚至呼吸困难、休克等临床表现,但常有高血压、动脉粥样硬化、冠心病史。体征、心电图和X线胸透有助于诊断。</li> <li>肺栓塞: 有胸痛、呼吸困难和紫绀等酷似自发性气胸的临床表现,但病人往往有咯血和低热,并常有下肢或盆腔栓塞性静脉炎、骨折、严重心脏病、心房纤颤等病史,或发生在长期卧床的老年患者。体检和X线检查有助于鉴别。</li> @@ -4638,21 +5135,26 @@ await prisma.$transaction(async tx => { </ol> </blockquote> <blockquote> -<p>__先天性肺大疱破裂也可以危及生命__,破裂时会并发自发性气胸,有突然胸痛,呼吸困难。若肺大疱破裂后形成活瓣,吸气时胸腔负压增高,气体进入胸腔,呼气时活瓣关闭,气体不能排出,尤其是咳嗽时,声门关闭气道压力增高,气体进入胸腔,声门开放后,气道压力减低,裂口又闭合,每一次呼吸和咳嗽都使胸腔内气体量增加,就形成张力性气胸。 张力性气胸时患侧肺组织完全萎缩,纵隔被推向健侧,在健侧肺组织亦被压缩的同时心脏大血管移位,大静脉扭曲变形,影响血液回流,造成呼吸循环严重障碍。有可能出现很快的心肺功能衰竭,导致死亡。</p> +<p><strong>先天性肺大疱破裂也可以危及生命</strong>,破裂时会并发自发性气胸,有突然胸痛,呼吸困难。若肺大疱破裂后形成活瓣,吸气时胸腔负压增高,气体进入胸腔,呼气时活瓣关闭,气体不能排出,尤其是咳嗽时,声门关闭气道压力增高,气体进入胸腔,声门开放后,气道压力减低,裂口又闭合,每一次呼吸和咳嗽都使胸腔内气体量增加,就形成张力性气胸。 张力性气胸时患侧肺组织完全萎缩,纵隔被推向健侧,在健侧肺组织亦被压缩的同时心脏大血管移位,大静脉扭曲变形,影响血液回流,造成呼吸循环严重障碍。有可能出现很快的心肺功能衰竭,导致死亡。</p> </blockquote> -<h2 id="急救"><a href="#急救" class="headerlink" title="急救"></a>急救</h2><ol> -<li><p>胸部损伤: 胸部如果被刺穿,需要立即覆盖伤处,并以凡士林或胶布密封,以免空气继续经伤处流入。无菌的胶布是较理想的选择, 但是所有气密的物质,例如玻璃纸和香烟盒也可以用。密封后,需要开一个小孔(振动筏)来使吸气时排出空气。胸部刺穿的患者需要密切监察,防止引发对生命有危险的张力性气胸。</p> +<h2 id="急救"><a class="header-anchor" href="#急救">¶</a>急救</h2> +<ol> +<li> +<p>胸部损伤: 胸部如果被刺穿,需要立即覆盖伤处,并以凡士林或胶布密封,以免空气继续经伤处流入。无菌的胶布是较理想的选择, 但是所有气密的物质,例如玻璃纸和香烟盒也可以用。密封后,需要开一个小孔(振动筏)来使吸气时排出空气。胸部刺穿的患者需要密切监察,防止引发对生命有危险的张力性气胸。</p> </li> -<li><p>入院前护理: 多数救护员可以进行针刺抽气, 以减低胸部的压力。 如果情况恶化,导管抽气也可能需要,包括有知觉的病人。可能的话,进行额外的治疗和即时送病人到医院治疗。没有经过适当的治疗的话,气胸患者是不能用飞机运送的。</p> +<li> +<p>入院前护理: 多数救护员可以进行针刺抽气, 以减低胸部的压力。 如果情况恶化,导管抽气也可能需要,包括有知觉的病人。可能的话,进行额外的治疗和即时送病人到医院治疗。没有经过适当的治疗的话,气胸患者是不能用飞机运送的。</p> </li> </ol> -<h2 id="流行病学"><a href="#流行病学" class="headerlink" title="流行病学"></a>流行病学</h2><p>经年龄调整后的年均发病率﹝AAIR﹞显示,男性患上气胸的机会较女性高出三至六倍。菲什曼在研究中提出以每十万人年计算,男女患上原发性气胸的AAIR分别为7.4和1.2。身高比平均值较高的人,他们患上气胸的AAIR也相对增加 - 至少为76英寸(1.93米)高的人,每十万人年约有200个案例。瘦削的身材也似乎增加了患上原发性气胸的风险。</p> +<h2 id="流行病学"><a class="header-anchor" href="#流行病学">¶</a>流行病学</h2> +<p>经年龄调整后的年均发病率﹝AAIR﹞显示,男性患上气胸的机会较女性高出三至六倍。菲什曼在研究中提出以每十万人年计算,男女患上原发性气胸的AAIR分别为7.4和1.2。身高比平均值较高的人,他们患上气胸的AAIR也相对增加 - 至少为76英寸(1.93米)高的人,每十万人年约有200个案例。瘦削的身材也似乎增加了患上原发性气胸的风险。</p> <p>此外,男性和女性烟民患上原发性气胸,相对于同性别的非吸烟者患上的机会高出约22倍和9倍。而个人吸烟的程度越凶,风险会有“大于线性”的效果:比方说每天吸食10支香烟的人,会比非吸烟者高出20倍患上气胸的机会;每天消耗20支香烟的,则会高出约100倍。</p> <p>在继发自发性气胸的病例当中,男性和女性的AAIR大概为6.3和2.0,而复发的风险则取决于患者本身有否任何潜在的肺病及其严重性。一旦发生了第二次气胸,病人之后再复发的机会极高。目前来说没有周详的研究调查儿童的发病率,但估计是每年约十万份之5至10。</p> <p>除外张力性气胸以外,因为气胸而死亡的案例是非常罕见的。据英国统计数字显示,每年每一百万人当中会有1.26位男性和0.62位女性会因为气胸死亡,其中中老年和继发性气胸的患者会有较高的死亡风险。</p> -<h2 id="引用"><a href="#引用" class="headerlink" title="引用"></a>引用</h2><ul> +<h2 id="引用"><a class="header-anchor" href="#引用">¶</a>引用</h2> +<ul> <li><a href="https://zhuanlan.zhihu.com/p/140951268">https://zhuanlan.zhihu.com/p/140951268</a></li> -<li><a href="https://www.yixue.com/%E6%B0%94%E8%83%B8">https://www.yixue.com/%E6%B0%94%E8%83%B8</a></li> +<li><a href="https://www.yixue.com/%E6%B0%94%E8%83%B8">https://www.yixue.com/气胸</a></li> <li><a href="https://zhuanlan.zhihu.com/p/84718122">https://zhuanlan.zhihu.com/p/84718122</a></li> </ul> ]]></content> @@ -4664,43 +5166,58 @@ await prisma.$transaction(async tx => { <title>灯笼草</title> <url>/2023/06/22/%E7%81%AF%E7%AC%BC%E8%8D%89/</url> <content><![CDATA[<p>今天在菜园子里看到了野生的灯笼草,都结果了:</p> -<p><img src="/img/%E7%94%9F%E6%B4%BB/%E7%81%AF%E7%AC%BC%E8%8D%89.jpg"></p> -<p>灯笼果别名为小果酸浆、秘鲁苦蘵、打头泡、灯笼草等,茄科酸浆属多年生草本植物。<br>灯笼果茎直立,叶较厚,阔卵形或心脏形,两面密生柔毛;花单独腋生,花萼阔钟状,花冠阔钟状,黄色而喉部有紫色斑纹,花丝及花药蓝紫色,花药长约3毫米。果萼薄纸质,淡绿色或淡黄色,浆果成熟时黄色,种子黄色,圆盘状,夏季开花结果。生于田间、路旁、村边。我国南北各地均有分市。</p> +<p><img src="/img/%E7%94%9F%E6%B4%BB/%E7%81%AF%E7%AC%BC%E8%8D%89.jpg" alt=""></p> +<p>灯笼果别名为小果酸浆、秘鲁苦蘵、打头泡、灯笼草等,茄科酸浆属多年生草本植物。<br> +灯笼果茎直立,叶较厚,阔卵形或心脏形,两面密生柔毛;花单独腋生,花萼阔钟状,花冠阔钟状,黄色而喉部有紫色斑纹,花丝及花药蓝紫色,花药长约3毫米。果萼薄纸质,淡绿色或淡黄色,浆果成熟时黄色,种子黄色,圆盘状,夏季开花结果。生于田间、路旁、村边。我国南北各地均有分市。</p> <p><strong>不要与<a href="https://en.wikipedia.org/wiki/Gooseberry">醋栗</a>混淆</strong></p> <p>醋栗长这样:</p> -<p><img src="/img/%E7%94%9F%E6%B4%BB/%E9%86%8B%E6%A0%97.jpg"></p> +<p><img src="/img/%E7%94%9F%E6%B4%BB/%E9%86%8B%E6%A0%97.jpg" alt=""></p> <hr> -<h2 id="性味"><a href="#性味" class="headerlink" title="性味"></a>性味</h2><ul> -<li><p>《陆川本草》:”甘淡,微寒。”</p> +<h2 id="性味"><a class="header-anchor" href="#性味">¶</a>性味</h2> +<ul> +<li> +<p>《陆川本草》:“甘淡,微寒。”</p> </li> -<li><p>《南宁市药物志》:”苦,寒,微甘。”</p> +<li> +<p>《南宁市药物志》:“苦,寒,微甘。”</p> </li> </ul> -<h2 id="功能主治"><a href="#功能主治" class="headerlink" title="功能主治"></a>功能主治</h2><blockquote> +<h2 id="功能主治"><a class="header-anchor" href="#功能主治">¶</a>功能主治</h2> +<blockquote> <p>清热,行气,止痛,消肿。治感冒,痄腮,喉痛,咳嗽,腹胀,疝气,天疱疮。</p> </blockquote> <ul> -<li><p>《陆川本草》:”行气,消胀,利尿。治腹胀,睾丸炎,疝气。”</p> +<li> +<p>《陆川本草》:“行气,消胀,利尿。治腹胀,睾丸炎,疝气。”</p> </li> -<li><p>《南宁市药物志》:”清热杀虫,止痛消肿。治热眼,喉痛,咳嗽;外敷毒疮,并熏洗阴囊肿大。”</p> +<li> +<p>《南宁市药物志》:“清热杀虫,止痛消肿。治热眼,喉痛,咳嗽;外敷毒疮,并熏洗阴囊肿大。”</p> </li> -<li><p>《生草药手册》:”内服治伤寒或小肠疝气。外洗治天疱疮。”</p> +<li> +<p>《生草药手册》:“内服治伤寒或小肠疝气。外洗治天疱疮。”</p> </li> -<li><p>《中国药植图鉴》:”功同酸浆。”</p> +<li> +<p>《中国药植图鉴》:“功同酸浆。”</p> </li> -<li><p>广州空军《常用中草药手册》:”治感冒发热,腮腺炎,支气管炎,疱疹,疖疮,疝气痛。”</p> +<li> +<p>广州空军《常用中草药手册》:“治感冒发热,腮腺炎,支气管炎,疱疹,疖疮,疝气痛。”</p> </li> </ul> -<h2 id="用法用量"><a href="#用法用量" class="headerlink" title="用法用量"></a>用法用量</h2><ul> +<h2 id="用法用量"><a class="header-anchor" href="#用法用量">¶</a>用法用量</h2> +<ul> <li>内服:煎汤,3 ~ 5钱。</li> <li>外用:捣敷或煎水洗。</li> </ul> -<h2 id="引用"><a href="#引用" class="headerlink" title="引用"></a>引用</h2><ul> -<li><p>《本草纲目》旧版草部第十六卷,草之五:燕京野果名红姑娘,外垂降囊,中含赤子如珠,酸甘可食盈盈绕砌,与翠草同芳,亦自可爱。捣计服治黄病(即黄胆性肝炎)多效,治上气咳嗽风热,明目,付小儿内辟等多种疾病。东北地区种植较广泛,其他地区种植较少,仍属稀特蔬菜。</p> +<h2 id="引用"><a class="header-anchor" href="#引用">¶</a>引用</h2> +<ul> +<li> +<p>《本草纲目》旧版草部第十六卷,草之五:燕京野果名红姑娘,外垂降囊,中含赤子如珠,酸甘可食盈盈绕砌,与翠草同芳,亦自可爱。捣计服治黄病(即黄胆性肝炎)多效,治上气咳嗽风热,明目,付小儿内辟等多种疾病。东北地区种植较广泛,其他地区种植较少,仍属稀特蔬菜。</p> </li> -<li><p>《别录》:“酸浆,生荆、楚川泽及人家田园中。五月采,阴干。”陶弘景:“酸浆,处处人家多有。叶亦可食。子作房,房中有子,如梅李大,皆黄赤色。”《唐本草》:“灯笼草,所在有之。八月采。枝干高三、四尺,有花,红色,状若灯笼,内有子,红色可爱。根、茎、花、叶并入药用。”</p> +<li> +<p>《别录》:“酸浆,生荆、楚川泽及人家田园中。五月采,阴干。”陶弘景:“酸浆,处处人家多有。叶亦可食。子作房,房中有子,如梅李大,皆黄赤色。”《唐本草》:“灯笼草,所在有之。八月采。枝干高三、四尺,有花,红色,状若灯笼,内有子,红色可爱。根、茎、花、叶并入药用。”</p> </li> -<li><p>《梦溪笔谈》:“苦耽,即本草酸浆也。河西番界中酸浆有盈丈者。”《本草衍义》:“酸浆,今天下皆有之。苗如天茄子,开小白花,结青壳,熟则深红,壳中子大如樱,亦红色,樱中复有细子,如落苏之子,食之有青草气。此即苦耽也。”</p> +<li> +<p>《梦溪笔谈》:“苦耽,即本草酸浆也。河西番界中酸浆有盈丈者。”《本草衍义》:“酸浆,今天下皆有之。苗如天茄子,开小白花,结青壳,熟则深红,壳中子大如樱,亦红色,樱中复有细子,如落苏之子,食之有青草气。此即苦耽也。”</p> </li> </ul> ]]></content> @@ -4724,25 +5241,30 @@ await prisma.$transaction(async tx => { <title>内护神经系统重点考点</title> <url>/2024/07/09/%E7%A5%9E%E7%BB%8F%E7%B3%BB%E7%BB%9F%E9%87%8D%E7%82%B9/</url> <content><![CDATA[<ol> -<li><p>十二对脑神经的顺序(一嗅二视三动眼,四滑五叉六外展,七面八听九舌咽,迷副舌下神经全):嗅神经、视神经、动眼神经、滑车神经、三叉神经、展神经、面神经、位听神经、舌咽神经、迷走神经、副神经和舌下神经。 </p> +<li> +<p>十二对脑神经的顺序(一嗅二视三动眼,四滑五叉六外展,七面八听九舌咽,迷副舌下神经全):嗅神经、视神经、动眼神经、滑车神经、三叉神经、展神经、面神经、位听神经、舌咽神经、迷走神经、副神经和舌下神经。</p> </li> -<li><p>脑干病变的特点:交叉性瘫痪、意识障碍、去大脑僵直、定位体征、脊髓。 </p> +<li> +<p>脑干病变的特点:交叉性瘫痪、意识障碍、去大脑僵直、定位体征、脊髓。</p> </li> -<li><p>瞳孔直径约为3-4mm,一般认为瞳孔直径<2mm为瞳孔缩小,>5mm为瞳孔散大。 </p> +<li> +<p>瞳孔直径约为3-4mm,一般认为瞳孔直径<2mm为瞳孔缩小,>5mm为瞳孔散大。</p> </li> -<li><p>正常脑脊液压力:80-180mmH2O。 </p> +<li> +<p>正常脑脊液压力:80-180mmH2O。</p> </li> -<li><p>意识障碍包括:</p> +<li> +<p>意识障碍包括:</p> <ul> -<li>嗜睡:是最轻的意识障碍,是一种病理性倦睡,患者陷入持续的睡眠状态,可被唤醒,并能正确回答和做出各种反应,但当刺激去除后很快又再入睡。 </li> -<li>昏睡:较嗜睡重,持续处于睡眠状态,强刺激方能唤醒,应答不切题。 </li> +<li>嗜睡:是最轻的意识障碍,是一种病理性倦睡,患者陷入持续的睡眠状态,可被唤醒,并能正确回答和做出各种反应,但当刺激去除后很快又再入睡。</li> +<li>昏睡:较嗜睡重,持续处于睡眠状态,强刺激方能唤醒,应答不切题。</li> <li>浅昏迷:对针刺和压眶由痛苦表情及躲避反应,无语言应答,各种反射无明显改变。</li> <li>深昏迷:意识全部丧失,强刺激也不能引起反应,肢体常呈弛缓状失。偶有深反射亢进与病理反射出现。机体仅能维持呼吸与血循环功能。</li> <li>意识模糊:较嗜睡为深的一种意识障碍,表现为定向障碍,思维和语言不连贯,可有和幻觉、躁动不安、谵语或精神错乱。</li> </ul> -<p> </p> </li> -<li><p>运动障碍的护理诊断:有失用综合征的危险的护理措施:</p> +<li> +<p>运动障碍的护理诊断:有失用综合征的危险的护理措施:</p> <ul> <li>早期康复干预:重视患侧刺激、保持良好的肢体位臵、体位变换(翻身)、床上运动训练(Bobath握手、桥式运动)</li> <li>恢复期运动训练</li> @@ -4750,25 +5272,29 @@ await prisma.$transaction(async tx => { </ul> <blockquote> <ul> -<li>急性炎症性脱髓鞘性多神经根病的临床表现中感觉障碍呈手套袜子样分布。 </li> +<li>急性炎症性脱髓鞘性多神经根病的临床表现中感觉障碍呈手套袜子样分布。</li> <li>重要特点是蛋白-细胞分离现象。</li> </ul> </blockquote> </li> -<li><p>脑血管疾病的分类</p> +<li> +<p>脑血管疾病的分类</p> <ul> <li>依据症状持续时间:短暂性脑缺血发作、脑卒中。</li> <li>依据病理性质:缺血性卒中、出血性卒中。</li> <li>依据发病急缓:急性脑血管疾病、慢性脑血管疾病。</li> </ul> </li> -<li><p>定义: 短暂性脑缺血发作(TIA):局造性脑缺血导致突发短暂的可逆性神经功能障碍。</p> +<li> +<p>定义: 短暂性脑缺血发作(TIA):局造性脑缺血导致突发短暂的可逆性神经功能障碍。</p> </li> -<li><p>脑血栓形成(脑血管病中最常见)</p> +<li> +<p>脑血栓形成(脑血管病中最常见)</p> +<ul> +<li>病因:最常见的病因是脑动脉粥样硬化,其次为脑动脉炎。高血压、高脂血症、糖尿病是加速脑血管硬化进展的重要因素。</li> +<li>检查:头颅CT:24小时后CT可见相应部位低密度影像。</li> +<li>急性期治疗: <ul> -<li>病因:最常见的病因是脑动脉粥样硬化,其次为脑动脉炎。高血压、高脂血症、糖尿病是加速脑血管硬化进展的重要因素。 </li> -<li>检查:头颅CT:24小时后CT可见相应部位低密度影像。 </li> -<li>急性期治疗:<ul> <li>早期溶栓:在发病后6小时以内进行溶栓。</li> <li>调整血压:急性期应维持病人血压于较平时稍高水平,血压过高(收缩压>220mmHg或舒张压>120mmHg)。</li> <li>抗血小板聚集。</li> @@ -4779,73 +5305,80 @@ await prisma.$transaction(async tx => { <li>外科治疗:开颅降压术。</li> <li>早期康复治疗。</li> </ul> -<p> </p> </li> -<li>用药护理:<ul> +<li>用药护理: +<ul> <li>溶栓和抗凝药物:严格掌握药物剂量,监测BT、PT、 APTT,观察有无黑便、牙龈出血、皮肤瘀点瘀斑等出血表现;观察有无并发颅内出血;观察有无栓子脱落所致其他部位栓塞的表现。</li> <li>甘露醇:监测尿量及尿液颜色;有无头痛、呕吐、意识障碍等低颅压综合征的表现。</li> </ul> -<p> </p> </li> -<li>饮食护理:<ul> +<li>饮食护理: +<ul> <li>体位选择:能坐者坐位进食,头略前屈,不能坐起者将床头摇起30°,头下垫枕头部前屈。</li> <li>食物选择:食物柔软、密度与性状均一;不易松散有一定黏度;能够变形;不易粘在黏膜上。</li> <li>吞咽方法选择:空吞咽和吞咽食物交替进行;侧方吞咽:吞咽时头侧向健侧肩部;点头样吞咽。</li> -<li>不能吞咽的病人给予鼻饲饮食。 <blockquote> +<li>不能吞咽的病人给予鼻饲饮食。 +<blockquote> <p>防止窒息:进食前应注意休息;保持进餐环境的安静、舒适;减少进餐时环境中分散注意力的干扰因素。</p> </blockquote> </li> </ul> </li> </ul> -<p> </p> </li> -<li><p>脑栓塞的病因:根据栓子来源可分为心源性、非心源性和来源不明性。心源性为最常见的原因,其中一半以上病人有风湿性心脏病二尖瓣狭窄合并心房颤动。</p> +<li> +<p>脑栓塞的病因:根据栓子来源可分为心源性、非心源性和来源不明性。心源性为最常见的原因,其中一半以上病人有风湿性心脏病二尖瓣狭窄合并心房颤动。</p> </li> -<li><p>脑出血临床特点:</p> +<li> +<p>脑出血临床特点:</p> <ul> <li>多见于50岁以上有高血压病史者,男性较女性多见,冬季发病率较高。</li> <li>体力活动或情绪激动时发病,多无前驱症状。</li> <li>起病较急,症状于数分钟至数小时达高峰。</li> <li>有肢体瘫痪、失语等局灶定位症状和剧烈头痛、喷射性呕吐、意识障碍等全脑症状。</li> -<li>发病时血压明显升高。(“三偏征”对侧偏瘫、偏身感觉障碍和同向性偏盲)。 <blockquote> -<p>头颅CT:确诊脑出血的首选检查方法,发病后即刻出现边界清楚的高密度影像。 </p> +<li>发病时血压明显升高。(“三偏征”对侧偏瘫、偏身感觉障碍和同向性偏盲)。</li> +</ul> +<blockquote> +<p>头颅CT:确诊脑出血的首选检查方法,发病后即刻出现边界清楚的高密度影像。</p> <p>治疗要点:治疗原则是脱水降颅压、调整血压、防止继续出血、减轻血肿所致继发性损害、促进神经功> 能恢复、加强护理防治并发症。</p> <ul> -<li>一般治疗:卧床休息,密切观察生命体征,保持呼吸道通畅,吸氧,保持肢体的功能位,鼻饲,预防感染,维持水、电解质平衡等。 </li> +<li>一般治疗:卧床休息,密切观察生命体征,保持呼吸道通畅,吸氧,保持肢体的功能位,鼻饲,预防感染,维持水、电解质平衡等。</li> <li>脱水降颅压:目的是控制脑水肿,药物:20%甘露醇。</li> -<li>调控血压:血压≥200/110mmHg时,可采取降压治疗,给予硫酸镁等。</li> +<li>调控血压:血压≥200/110mmHg时,可采取降压治疗,给予硫酸镁等。</li> <li>止血和凝血治疗。</li> -<li>外科治疗:壳核出血量>30ml,小脑或丘脑出血>10ml(6)康复治疗。 </li> +<li>外科治疗:壳核出血量>30ml,小脑或丘脑出血>10ml(6)康复治疗。</li> <li>休息与安全:绝对卧床休息2~4周,抬高床头15~30度,减轻脑水肿。</li> </ul> </blockquote> </li> -</ul> -<p> </p> -</li> -<li><p>帕金森病的临床表现:</p> +<li> +<p>帕金森病的临床表现:</p> <ul> <li>静止性震颤:多从一侧开始,类似“搓丸”样动作,静止时明显震颤,动作时减轻,精神紧张时加重,入睡后消失。</li> <li>肌强直:“铅管样强直”、“齿轮样强直”。</li> -<li>运动迟缓:“小写症”“面具脸”。 </li> +<li>运动迟缓:“小写症”“面具脸”。</li> <li>姿势步态异常:“慌张步态”。</li> </ul> </li> -<li><p>癫痫持续状态在给氧、防护的从速制止发作,首先给地西泮10~20mg静脉注射,注射速度不超过每分钟2mg,以免抑制呼吸,在监测血压同时静脉滴入苯妥英钠以控制发作。 </p> +<li> +<p>癫痫持续状态在给氧、防护的从速制止发作,首先给地西泮10~20mg静脉注射,注射速度不超过每分钟2mg,以免抑制呼吸,在监测血压同时静脉滴入苯妥英钠以控制发作。</p> </li> -<li><p>癫痫的护理诊断:</p> +<li> +<p>癫痫的护理诊断:</p> <ul> <li>防窒息</li> <li>防受伤:活动状态时发作,陪伴者应立即将病人缓慢臵于平卧位,防止外伤,抽搐肢体不可用力按压,以免造成骨折或关节脱位。</li> </ul> </li> -<li><p>重症肌无力的临床特点:</p> +<li> +<p>重症肌无力的临床特点:</p> <ul> -<li>是一种与胸腺异常有关的自身免疫性疾病。 </li> -<li>最先表现为一侧眼睑下垂。 </li> +<li>是一种与胸腺异常有关的自身免疫性疾病。</li> +<li>最先表现为一侧眼睑下垂。</li> <li>肌无力呈进行性发展逐渐累及其他肌肉。</li> -<li>症状晨轻暮重、活动后重,休息后轻。 <blockquote> +<li>症状晨轻暮重、活动后重,休息后轻。</li> +</ul> +<blockquote> <p>实验室检查:</p> <ul> <li>疲劳试验(Jolly试验):嘱病人用力眨眼30次后眼裂明显变小或两臂持续平举后出现上臂下垂。</li> @@ -4853,50 +5386,64 @@ await prisma.$transaction(async tx => { </ul> </blockquote> </li> -</ul> -<p> </p> -</li> -<li><p>腰椎穿刺术后护理嘱病人去枕平卧4~6小时,不可抬高头部,观察有无并发症,如头痛、腰背痛、脑疝、感染。 </p> +<li> +<p>腰椎穿刺术后护理嘱病人去枕平卧4~6小时,不可抬高头部,观察有无并发症,如头痛、腰背痛、脑疝、感染。</p> </li> -<li><p>意识障碍按程度可分为嗜睡、昏睡、浅昏迷、中昏迷、深昏迷。 </p> +<li> +<p>意识障碍按程度可分为嗜睡、昏睡、浅昏迷、中昏迷、深昏迷。</p> </li> -<li><p>脑出血病人急性期治疗的主要原则是防止再出血、控制脑水肿、减低颅内压、维持生命功能、防治并发症。 </p> +<li> +<p>脑出血病人急性期治疗的主要原则是防止再出血、控制脑水肿、减低颅内压、维持生命功能、防治并发症。</p> </li> -<li><p>根据癫痫发作的临床表现和脑电图特点,可将癫痫分为部分性发作、全面性发作、不能分类的癫痫发作3大类。 </p> +<li> +<p>根据癫痫发作的临床表现和脑电图特点,可将癫痫分为部分性发作、全面性发作、不能分类的癫痫发作3大类。</p> <blockquote> -<p>癫痫全面性强直–阵挛发作过程可分为强直期、阵挛期、痉挛后三期。 </p> +<p>癫痫全面性强直–阵挛发作过程可分为强直期、阵挛期、痉挛后三期。</p> </blockquote> </li> -<li><p>诊断癫痫最有价值的检查是脑电图。 </p> +<li> +<p>诊断癫痫最有价值的检查是脑电图。</p> </li> -<li><p>脑动脉粥样硬化是脑血栓形成最常见的病因。 </p> +<li> +<p>脑动脉粥样硬化是脑血栓形成最常见的病因。</p> </li> -<li><p>蛛网膜下腔出血病人应绝对卧床4-6周周,避免用力排便情绪激动等。 </p> +<li> +<p>蛛网膜下腔出血病人应绝对卧床4-6周周,避免用力排便情绪激动等。</p> </li> -<li><p>三偏症指偏瘫,偏盲,偏麻(偏身感觉障碍)。 </p> +<li> +<p>三偏症指偏瘫,偏盲,偏麻(偏身感觉障碍)。</p> </li> -<li><p>吉兰——巴雷的主要危险是呼吸麻痹。 </p> +<li> +<p>吉兰——巴雷的主要危险是呼吸麻痹。</p> </li> -<li><p>脑血管发病最重要的危险因素是高血压,心脏病,糖尿病,TIA。 </p> +<li> +<p>脑血管发病最重要的危险因素是高血压,心脏病,糖尿病,TIA。</p> </li> -<li><p>TIA指脑缺血症状24小时内可以完全恢复。 </p> +<li> +<p>TIA指脑缺血症状24小时内可以完全恢复。</p> </li> -<li><p>早期溶栓指发病6小时内进行溶栓处理。 </p> +<li> +<p>早期溶栓指发病6小时内进行溶栓处理。</p> </li> -<li><p>脑组织中豆纹动脉动脉最容易出血。 </p> +<li> +<p>脑组织中豆纹动脉动脉最容易出血。</p> </li> -<li><p>一般20%甘露醇200ml静脉滴注30分钟分钟内滴完。输入甘露醇后4小时内尿量少于200毫升ml要慎用或停用。 </p> +<li> +<p>一般20%甘露醇200ml静脉滴注30分钟分钟内滴完。输入甘露醇后4小时内尿量少于200毫升ml要慎用或停用。</p> </li> -<li><p>蛛网膜下腔出血的特征性体征是脑膜刺激征,特征性实验室检查是脑脊液检查。 </p> +<li> +<p>蛛网膜下腔出血的特征性体征是脑膜刺激征,特征性实验室检查是脑脊液检查。</p> </li> -<li><p>脑血栓形成常在安静时发病,脑出血常在活动及情绪激动时发病。 </p> +<li> +<p>脑血栓形成常在安静时发病,脑出血常在活动及情绪激动时发病。</p> </li> -<li><p>简述癫痫持续状态的护理要点:(1)迅速控制发作(安定10~20mg静脉慢推)(2)用床挡,专人守护,必要时用约束带(3)移开周围物品(4)立即取下假牙、垫牙,保护皮肤,不用力按压病人(5)解开衣领,头偏一侧,保持气道通畅(6)观察生命体征、神志。 </p> +<li> +<p>简述癫痫持续状态的护理要点:(1)迅速控制发作(安定10~20mg静脉慢推)(2)用床挡,专人守护,必要时用约束带(3)移开周围物品(4)立即取下假牙、垫牙,保护皮肤,不用力按压病人(5)解开衣领,头偏一侧,保持气道通畅(6)观察生命体征、神志。</p> </li> -<li><p>名词解释:短暂性脑缺血发作、癫痫、癫痫持续状态、帕金森病。</p> +<li> +<p>名词解释:短暂性脑缺血发作、癫痫、癫痫持续状态、帕金森病。</p> </li> </ol> -<p> </p> ]]></content> <tags> <tag>Medicine</tag> @@ -4905,15 +5452,20 @@ await prisma.$transaction(async tx => { <entry> <title>纯牛奶可以加点啥</title> <url>/2023/03/01/%E7%BA%AF%E7%89%9B%E5%A5%B6%E5%8F%AF%E4%BB%A5%E5%8A%A0%E7%82%B9%E5%95%A5/</url> - <content><![CDATA[<h2 id="糖"><a href="#糖" class="headerlink" title="糖"></a>糖</h2><p>纯牛奶加糖可以增加碳水化合物所供给的能量,建议加蔗糖,因为蔗糖在进入消化道被消化液分解后,会变成葡萄糖而被人体吸收,一般是每100毫升牛奶加5-8克糖,即5%-8%的比例。</p> + <content><![CDATA[<h2 id="糖"><a class="header-anchor" href="#糖">¶</a>糖</h2> +<p>纯牛奶加糖可以增加碳水化合物所供给的能量,建议加蔗糖,因为蔗糖在进入消化道被消化液分解后,会变成葡萄糖而被人体吸收,一般是每100毫升牛奶加5-8克糖,即5%-8%的比例。</p> <p>牛奶中的蛋白质80%为酪蛋白,当牛奶的酸碱度在4.6以下时,大量的酪蛋白会发生凝集、沉淀,难以消化吸收,严重者还可能导致消化不良或腹泻。所以牛奶中不宜添加果汁等酸性饮料。</p> -<p>需要注意的是:牛奶中含有的赖氨酸在加热条件下能与果糖反应,生成有毒的果糖基赖氨酸,有害于人体,<strong>鲜牛奶在煮沸时不要加糖。</strong><br>此外,红糖里的酸性物质会把牛奶凝结成块,不好吃也不利于吸收。</p> -<h2 id="蜂蜜"><a href="#蜂蜜" class="headerlink" title="蜂蜜"></a>蜂蜜</h2><p>纯牛奶和纯蜂蜜是一个非常好的搭配,牛奶和蜂蜜之间不存在任何成分反应。蜂蜜中含有丰富的葡萄糖和果糖,属于单糖,可以直接被人体吸收,不会给肠胃造成负担,纯牛奶含有丰富的蛋白质和钙,营养成分丰富,所以纯牛奶加蜂蜜,可以更全面地补充营养。</p> -<h2 id="其他"><a href="#其他" class="headerlink" title="其他"></a>其他</h2><ol> +<p>需要注意的是:牛奶中含有的赖氨酸在加热条件下能与果糖反应,生成有毒的果糖基赖氨酸,有害于人体,<strong>鲜牛奶在煮沸时不要加糖。</strong><br> +此外,红糖里的酸性物质会把牛奶凝结成块,不好吃也不利于吸收。</p> +<h2 id="蜂蜜"><a class="header-anchor" href="#蜂蜜">¶</a>蜂蜜</h2> +<p>纯牛奶和纯蜂蜜是一个非常好的搭配,牛奶和蜂蜜之间不存在任何成分反应。蜂蜜中含有丰富的葡萄糖和果糖,属于单糖,可以直接被人体吸收,不会给肠胃造成负担,纯牛奶含有丰富的蛋白质和钙,营养成分丰富,所以纯牛奶加蜂蜜,可以更全面地补充营养。</p> +<h2 id="其他"><a class="header-anchor" href="#其他">¶</a>其他</h2> +<ol> <li>对于巧克力:牛奶含有丰富的蛋白质和钙,而巧克力含有草酸,两者同食会结合成不溶性草酸钙,极大影响钙的吸收,甚至会出现头发干枯、腹泻、生长缓慢等现象。</li> <li>对于药物:由于牛奶容易在药物表面形成一个覆盖膜,使奶中的钙、镁等矿物质与药物发生化学反应,形成非水溶性物质,从而影响药效。</li> </ol> -<h2 id="引用"><a href="#引用" class="headerlink" title="引用"></a>引用</h2><ul> +<h2 id="引用"><a class="header-anchor" href="#引用">¶</a>引用</h2> +<ul> <li><a href="https://zhuanlan.zhihu.com/p/140951268">https://zhuanlan.zhihu.com/p/140951268</a></li> <li><a href="https://www.zhihu.com/question/480023755">https://www.zhihu.com/question/480023755</a></li> </ul> @@ -4949,34 +5501,41 @@ await prisma.$transaction(async tx => { <entry> <title>肝功能检查化验单阅读指南</title> <url>/2023/10/13/%E8%82%9D%E5%8A%9F%E8%83%BD%E6%A3%80%E6%9F%A5%E5%8C%96%E9%AA%8C%E5%8D%95/</url> - <content><![CDATA[<p><img src="/img/%E5%8C%BB%E5%AD%A6/%E8%82%9D%E5%8A%9F%E8%83%BD%E6%A3%80%E6%9F%A5%E5%8C%96%E9%AA%8C%E5%8D%95Demo.jpeg"></p> + <content><![CDATA[<p><img src="/img/%E5%8C%BB%E5%AD%A6/%E8%82%9D%E5%8A%9F%E8%83%BD%E6%A3%80%E6%9F%A5%E5%8C%96%E9%AA%8C%E5%8D%95Demo.jpeg" alt=""></p> <ul> -<li><p>谷丙转氨酶 (ALT)</p> +<li> +<p>谷丙转氨酶 (ALT)</p> <ul> <li>正常情况: <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.566ex;" xmlns="http://www.w3.org/2000/svg" width="6.67ex" height="2.262ex" role="img" focusable="false" viewBox="0 -750 2948 1000"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="mn"><path data-c="34" d="M462 0Q444 3 333 3Q217 3 199 0H190V46H221Q241 46 248 46T265 48T279 53T286 61Q287 63 287 115V165H28V211L179 442Q332 674 334 675Q336 677 355 677H373L379 671V211H471V165H379V114Q379 73 379 66T385 54Q393 47 442 46H471V0H462ZM293 211V545L74 212L183 211H293Z"></path><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z" transform="translate(500,0)"></path></g><g data-mml-node="mi" transform="translate(1000,0)"><path data-c="1D448" d="M107 637Q73 637 71 641Q70 643 70 649Q70 673 81 682Q83 683 98 683Q139 681 234 681Q268 681 297 681T342 682T362 682Q378 682 378 672Q378 670 376 658Q371 641 366 638H364Q362 638 359 638T352 638T343 637T334 637Q295 636 284 634T266 623Q265 621 238 518T184 302T154 169Q152 155 152 140Q152 86 183 55T269 24Q336 24 403 69T501 205L552 406Q599 598 599 606Q599 633 535 637Q511 637 511 648Q511 650 513 660Q517 676 519 679T529 683Q532 683 561 682T645 680Q696 680 723 681T752 682Q767 682 767 672Q767 650 759 642Q756 637 737 637Q666 633 648 597Q646 592 598 404Q557 235 548 205Q515 105 433 42T263 -22Q171 -22 116 34T60 167V183Q60 201 115 421Q164 622 164 628Q164 635 107 637Z"></path></g><g data-mml-node="TeXAtom" data-mjx-texclass="ORD" transform="translate(1767,0)"><g data-mml-node="mo"><path data-c="2F" d="M423 750Q432 750 438 744T444 730Q444 725 271 248T92 -240Q85 -250 75 -250Q68 -250 62 -245T56 -231Q56 -221 230 257T407 740Q411 750 423 750Z"></path></g></g><g data-mml-node="mi" transform="translate(2267,0)"><path data-c="1D43F" d="M228 637Q194 637 192 641Q191 643 191 649Q191 673 202 682Q204 683 217 683Q271 680 344 680Q485 680 506 683H518Q524 677 524 674T522 656Q517 641 513 637H475Q406 636 394 628Q387 624 380 600T313 336Q297 271 279 198T252 88L243 52Q243 48 252 48T311 46H328Q360 46 379 47T428 54T478 72T522 106T564 161Q580 191 594 228T611 270Q616 273 628 273H641Q647 264 647 262T627 203T583 83T557 9Q555 4 553 3T537 0T494 -1Q483 -1 418 -1T294 0H116Q32 0 32 10Q32 17 34 24Q39 43 44 45Q48 46 59 46H65Q92 46 125 49Q139 52 144 61Q147 65 216 339T285 628Q285 635 228 637Z"></path></g></g></g></svg></mjx-container></li> -<li>异常情况:<ul> +<li>异常情况: +<ul> <li>升高: 可见于肝胆疾病, 急慢性肝炎, 胆石症引起的胆道梗阻等,某些药物造成的肝脏损伤也可引起</li> </ul> </li> </ul> </li> -<li><p>谷草转氨酶 (AST)</p> +<li> +<p>谷草转氨酶 (AST)</p> <ul> <li>正常情况: <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.566ex;" xmlns="http://www.w3.org/2000/svg" width="6.67ex" height="2.262ex" role="img" focusable="false" viewBox="0 -750 2948 1000"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="mn"><path data-c="34" d="M462 0Q444 3 333 3Q217 3 199 0H190V46H221Q241 46 248 46T265 48T279 53T286 61Q287 63 287 115V165H28V211L179 442Q332 674 334 675Q336 677 355 677H373L379 671V211H471V165H379V114Q379 73 379 66T385 54Q393 47 442 46H471V0H462ZM293 211V545L74 212L183 211H293Z"></path><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z" transform="translate(500,0)"></path></g><g data-mml-node="mi" transform="translate(1000,0)"><path data-c="1D448" d="M107 637Q73 637 71 641Q70 643 70 649Q70 673 81 682Q83 683 98 683Q139 681 234 681Q268 681 297 681T342 682T362 682Q378 682 378 672Q378 670 376 658Q371 641 366 638H364Q362 638 359 638T352 638T343 637T334 637Q295 636 284 634T266 623Q265 621 238 518T184 302T154 169Q152 155 152 140Q152 86 183 55T269 24Q336 24 403 69T501 205L552 406Q599 598 599 606Q599 633 535 637Q511 637 511 648Q511 650 513 660Q517 676 519 679T529 683Q532 683 561 682T645 680Q696 680 723 681T752 682Q767 682 767 672Q767 650 759 642Q756 637 737 637Q666 633 648 597Q646 592 598 404Q557 235 548 205Q515 105 433 42T263 -22Q171 -22 116 34T60 167V183Q60 201 115 421Q164 622 164 628Q164 635 107 637Z"></path></g><g data-mml-node="TeXAtom" data-mjx-texclass="ORD" transform="translate(1767,0)"><g data-mml-node="mo"><path data-c="2F" d="M423 750Q432 750 438 744T444 730Q444 725 271 248T92 -240Q85 -250 75 -250Q68 -250 62 -245T56 -231Q56 -221 230 257T407 740Q411 750 423 750Z"></path></g></g><g data-mml-node="mi" transform="translate(2267,0)"><path data-c="1D43F" d="M228 637Q194 637 192 641Q191 643 191 649Q191 673 202 682Q204 683 217 683Q271 680 344 680Q485 680 506 683H518Q524 677 524 674T522 656Q517 641 513 637H475Q406 636 394 628Q387 624 380 600T313 336Q297 271 279 198T252 88L243 52Q243 48 252 48T311 46H328Q360 46 379 47T428 54T478 72T522 106T564 161Q580 191 594 228T611 270Q616 273 628 273H641Q647 264 647 262T627 203T583 83T557 9Q555 4 553 3T537 0T494 -1Q483 -1 418 -1T294 0H116Q32 0 32 10Q32 17 34 24Q39 43 44 45Q48 46 59 46H65Q92 46 125 49Q139 52 144 61Q147 65 216 339T285 628Q285 635 228 637Z"></path></g></g></g></svg></mjx-container></li> -<li>异常情况:<ul> +<li>异常情况: +<ul> <li>升高: 可见于急慢性肝炎等肝脏疾病以及某些药物的毒副作用, 与ALT主要提示肝脏疾病不同,AST还可以存在于心肌,骨骼肌,肾脏,所以AST升高还可见于心肌梗死,心肌炎,肌溶解等疾病。</li> </ul> </li> </ul> </li> -<li><p>血清胆红素</p> +<li> +<p>血清胆红素</p> +<ul> +<li>正常情况: <ul> -<li>正常情况:<ul> <li>总胆红素 (TBLL): <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.566ex;" xmlns="http://www.w3.org/2000/svg" width="16.971ex" height="2.262ex" role="img" focusable="false" viewBox="0 -750 7501 1000"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="mn"><path data-c="32" d="M109 429Q82 429 66 447T50 491Q50 562 103 614T235 666Q326 666 387 610T449 465Q449 422 429 383T381 315T301 241Q265 210 201 149L142 93L218 92Q375 92 385 97Q392 99 409 186V189H449V186Q448 183 436 95T421 3V0H50V19V31Q50 38 56 46T86 81Q115 113 136 137Q145 147 170 174T204 211T233 244T261 278T284 308T305 340T320 369T333 401T340 431T343 464Q343 527 309 573T212 619Q179 619 154 602T119 569T109 550Q109 549 114 549Q132 549 151 535T170 489Q170 464 154 447T109 429Z"></path></g><g data-mml-node="mo" transform="translate(722.2,0)"><path data-c="2212" d="M84 237T84 250T98 270H679Q694 262 694 250T679 230H98Q84 237 84 250Z"></path></g><g data-mml-node="mn" transform="translate(1722.4,0)"><path data-c="31" d="M213 578L200 573Q186 568 160 563T102 556H83V602H102Q149 604 189 617T245 641T273 663Q275 666 285 666Q294 666 302 660V361L303 61Q310 54 315 52T339 48T401 46H427V0H416Q395 3 257 3Q121 3 100 0H88V46H114Q136 46 152 46T177 47T193 50T201 52T207 57T213 61V578Z"></path><path data-c="39" d="M352 287Q304 211 232 211Q154 211 104 270T44 396Q42 412 42 436V444Q42 537 111 606Q171 666 243 666Q245 666 249 666T257 665H261Q273 665 286 663T323 651T370 619T413 560Q456 472 456 334Q456 194 396 97Q361 41 312 10T208 -22Q147 -22 108 7T68 93T121 149Q143 149 158 135T173 96Q173 78 164 65T148 49T135 44L131 43Q131 41 138 37T164 27T206 22H212Q272 22 313 86Q352 142 352 280V287ZM244 248Q292 248 321 297T351 430Q351 508 343 542Q341 552 337 562T323 588T293 615T246 625Q208 625 181 598Q160 576 154 546T147 441Q147 358 152 329T172 282Q197 248 244 248Z" transform="translate(500,0)"></path></g><g data-mml-node="mi" transform="translate(2722.4,0)"><path data-c="1D707" d="M58 -216Q44 -216 34 -208T23 -186Q23 -176 96 116T173 414Q186 442 219 442Q231 441 239 435T249 423T251 413Q251 401 220 279T187 142Q185 131 185 107V99Q185 26 252 26Q261 26 270 27T287 31T302 38T315 45T327 55T338 65T348 77T356 88T365 100L372 110L408 253Q444 395 448 404Q461 431 491 431Q504 431 512 424T523 412T525 402L449 84Q448 79 448 68Q448 43 455 35T476 26Q485 27 496 35Q517 55 537 131Q543 151 547 152Q549 153 557 153H561Q580 153 580 144Q580 138 575 117T555 63T523 13Q510 0 491 -8Q483 -10 467 -10Q446 -10 429 -4T402 11T385 29T376 44T374 51L368 45Q362 39 350 30T324 12T288 -4T246 -11Q199 -11 153 12L129 -85Q108 -167 104 -180T92 -202Q76 -216 58 -216Z"></path></g><g data-mml-node="mo" transform="translate(3603.2,0)"><path data-c="3E" d="M84 520Q84 528 88 533T96 539L99 540Q106 540 253 471T544 334L687 265Q694 260 694 250T687 235Q685 233 395 96L107 -40H101Q83 -38 83 -20Q83 -19 83 -17Q82 -10 98 -1Q117 9 248 71Q326 108 378 132L626 250L378 368Q90 504 86 509Q84 513 84 520Z"></path></g><g data-mml-node="mi" transform="translate(4659,0)"><path data-c="1D45A" d="M21 287Q22 293 24 303T36 341T56 388T88 425T132 442T175 435T205 417T221 395T229 376L231 369Q231 367 232 367L243 378Q303 442 384 442Q401 442 415 440T441 433T460 423T475 411T485 398T493 385T497 373T500 364T502 357L510 367Q573 442 659 442Q713 442 746 415T780 336Q780 285 742 178T704 50Q705 36 709 31T724 26Q752 26 776 56T815 138Q818 149 821 151T837 153Q857 153 857 145Q857 144 853 130Q845 101 831 73T785 17T716 -10Q669 -10 648 17T627 73Q627 92 663 193T700 345Q700 404 656 404H651Q565 404 506 303L499 291L466 157Q433 26 428 16Q415 -11 385 -11Q372 -11 364 -4T353 8T350 18Q350 29 384 161L420 307Q423 322 423 345Q423 404 379 404H374Q288 404 229 303L222 291L189 157Q156 26 151 16Q138 -11 108 -11Q95 -11 87 -5T76 7T74 17Q74 30 112 181Q151 335 151 342Q154 357 154 369Q154 405 129 405Q107 405 92 377T69 316T57 280Q55 278 41 278H27Q21 284 21 287Z"></path></g><g data-mml-node="mi" transform="translate(5537,0)"><path data-c="1D45C" d="M201 -11Q126 -11 80 38T34 156Q34 221 64 279T146 380Q222 441 301 441Q333 441 341 440Q354 437 367 433T402 417T438 387T464 338T476 268Q476 161 390 75T201 -11ZM121 120Q121 70 147 48T206 26Q250 26 289 58T351 142Q360 163 374 216T388 308Q388 352 370 375Q346 405 306 405Q243 405 195 347Q158 303 140 230T121 120Z"></path></g><g data-mml-node="mi" transform="translate(6022,0)"><path data-c="1D459" d="M117 59Q117 26 142 26Q179 26 205 131Q211 151 215 152Q217 153 225 153H229Q238 153 241 153T246 151T248 144Q247 138 245 128T234 90T214 43T183 6T137 -11Q101 -11 70 11T38 85Q38 97 39 102L104 360Q167 615 167 623Q167 626 166 628T162 632T157 634T149 635T141 636T132 637T122 637Q112 637 109 637T101 638T95 641T94 647Q94 649 96 661Q101 680 107 682T179 688Q194 689 213 690T243 693T254 694Q266 694 266 686Q266 675 193 386T118 83Q118 81 118 75T117 65V59Z"></path></g><g data-mml-node="TeXAtom" data-mjx-texclass="ORD" transform="translate(6320,0)"><g data-mml-node="mo"><path data-c="2F" d="M423 750Q432 750 438 744T444 730Q444 725 271 248T92 -240Q85 -250 75 -250Q68 -250 62 -245T56 -231Q56 -221 230 257T407 740Q411 750 423 750Z"></path></g></g><g data-mml-node="mi" transform="translate(6820,0)"><path data-c="1D43F" d="M228 637Q194 637 192 641Q191 643 191 649Q191 673 202 682Q204 683 217 683Q271 680 344 680Q485 680 506 683H518Q524 677 524 674T522 656Q517 641 513 637H475Q406 636 394 628Q387 624 380 600T313 336Q297 271 279 198T252 88L243 52Q243 48 252 48T311 46H328Q360 46 379 47T428 54T478 72T522 106T564 161Q580 191 594 228T611 270Q616 273 628 273H641Q647 264 647 262T627 203T583 83T557 9Q555 4 553 3T537 0T494 -1Q483 -1 418 -1T294 0H116Q32 0 32 10Q32 17 34 24Q39 43 44 45Q48 46 59 46H65Q92 46 125 49Q139 52 144 61Q147 65 216 339T285 628Q285 635 228 637Z"></path></g></g></g></svg></mjx-container></li> <li>直接胆红素 (DBIL): <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.566ex;" xmlns="http://www.w3.org/2000/svg" width="19.353ex" height="2.262ex" role="img" focusable="false" viewBox="0 -750 8554 1000"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="mn"><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z"></path></g><g data-mml-node="mo" transform="translate(722.2,0)"><path data-c="2212" d="M84 237T84 250T98 270H679Q694 262 694 250T679 230H98Q84 237 84 250Z"></path></g><g data-mml-node="mn" transform="translate(1722.4,0)"><path data-c="36" d="M42 313Q42 476 123 571T303 666Q372 666 402 630T432 550Q432 525 418 510T379 495Q356 495 341 509T326 548Q326 592 373 601Q351 623 311 626Q240 626 194 566Q147 500 147 364L148 360Q153 366 156 373Q197 433 263 433H267Q313 433 348 414Q372 400 396 374T435 317Q456 268 456 210V192Q456 169 451 149Q440 90 387 34T253 -22Q225 -22 199 -14T143 16T92 75T56 172T42 313ZM257 397Q227 397 205 380T171 335T154 278T148 216Q148 133 160 97T198 39Q222 21 251 21Q302 21 329 59Q342 77 347 104T352 209Q352 289 347 316T329 361Q302 397 257 397Z"></path><path data-c="2E" d="M78 60Q78 84 95 102T138 120Q162 120 180 104T199 61Q199 36 182 18T139 0T96 17T78 60Z" transform="translate(500,0)"></path><path data-c="38" d="M70 417T70 494T124 618T248 666Q319 666 374 624T429 515Q429 485 418 459T392 417T361 389T335 371T324 363L338 354Q352 344 366 334T382 323Q457 264 457 174Q457 95 399 37T249 -22Q159 -22 101 29T43 155Q43 263 172 335L154 348Q133 361 127 368Q70 417 70 494ZM286 386L292 390Q298 394 301 396T311 403T323 413T334 425T345 438T355 454T364 471T369 491T371 513Q371 556 342 586T275 624Q268 625 242 625Q201 625 165 599T128 534Q128 511 141 492T167 463T217 431Q224 426 228 424L286 386ZM250 21Q308 21 350 55T392 137Q392 154 387 169T375 194T353 216T330 234T301 253T274 270Q260 279 244 289T218 306L210 311Q204 311 181 294T133 239T107 157Q107 98 150 60T250 21Z" transform="translate(778,0)"></path><path data-c="34" d="M462 0Q444 3 333 3Q217 3 199 0H190V46H221Q241 46 248 46T265 48T279 53T286 61Q287 63 287 115V165H28V211L179 442Q332 674 334 675Q336 677 355 677H373L379 671V211H471V165H379V114Q379 73 379 66T385 54Q393 47 442 46H471V0H462ZM293 211V545L74 212L183 211H293Z" transform="translate(1278,0)"></path></g><g data-mml-node="mo" transform="translate(3778.2,0)"><path data-c="3E" d="M84 520Q84 528 88 533T96 539L99 540Q106 540 253 471T544 334L687 265Q694 260 694 250T687 235Q685 233 395 96L107 -40H101Q83 -38 83 -20Q83 -19 83 -17Q82 -10 98 -1Q117 9 248 71Q326 108 378 132L626 250L378 368Q90 504 86 509Q84 513 84 520Z"></path></g><g data-mml-node="mi" transform="translate(4834,0)"><path data-c="1D45A" d="M21 287Q22 293 24 303T36 341T56 388T88 425T132 442T175 435T205 417T221 395T229 376L231 369Q231 367 232 367L243 378Q303 442 384 442Q401 442 415 440T441 433T460 423T475 411T485 398T493 385T497 373T500 364T502 357L510 367Q573 442 659 442Q713 442 746 415T780 336Q780 285 742 178T704 50Q705 36 709 31T724 26Q752 26 776 56T815 138Q818 149 821 151T837 153Q857 153 857 145Q857 144 853 130Q845 101 831 73T785 17T716 -10Q669 -10 648 17T627 73Q627 92 663 193T700 345Q700 404 656 404H651Q565 404 506 303L499 291L466 157Q433 26 428 16Q415 -11 385 -11Q372 -11 364 -4T353 8T350 18Q350 29 384 161L420 307Q423 322 423 345Q423 404 379 404H374Q288 404 229 303L222 291L189 157Q156 26 151 16Q138 -11 108 -11Q95 -11 87 -5T76 7T74 17Q74 30 112 181Q151 335 151 342Q154 357 154 369Q154 405 129 405Q107 405 92 377T69 316T57 280Q55 278 41 278H27Q21 284 21 287Z"></path></g><g data-mml-node="mi" transform="translate(5712,0)"><path data-c="1D45A" d="M21 287Q22 293 24 303T36 341T56 388T88 425T132 442T175 435T205 417T221 395T229 376L231 369Q231 367 232 367L243 378Q303 442 384 442Q401 442 415 440T441 433T460 423T475 411T485 398T493 385T497 373T500 364T502 357L510 367Q573 442 659 442Q713 442 746 415T780 336Q780 285 742 178T704 50Q705 36 709 31T724 26Q752 26 776 56T815 138Q818 149 821 151T837 153Q857 153 857 145Q857 144 853 130Q845 101 831 73T785 17T716 -10Q669 -10 648 17T627 73Q627 92 663 193T700 345Q700 404 656 404H651Q565 404 506 303L499 291L466 157Q433 26 428 16Q415 -11 385 -11Q372 -11 364 -4T353 8T350 18Q350 29 384 161L420 307Q423 322 423 345Q423 404 379 404H374Q288 404 229 303L222 291L189 157Q156 26 151 16Q138 -11 108 -11Q95 -11 87 -5T76 7T74 17Q74 30 112 181Q151 335 151 342Q154 357 154 369Q154 405 129 405Q107 405 92 377T69 316T57 280Q55 278 41 278H27Q21 284 21 287Z"></path></g><g data-mml-node="mi" transform="translate(6590,0)"><path data-c="1D45C" d="M201 -11Q126 -11 80 38T34 156Q34 221 64 279T146 380Q222 441 301 441Q333 441 341 440Q354 437 367 433T402 417T438 387T464 338T476 268Q476 161 390 75T201 -11ZM121 120Q121 70 147 48T206 26Q250 26 289 58T351 142Q360 163 374 216T388 308Q388 352 370 375Q346 405 306 405Q243 405 195 347Q158 303 140 230T121 120Z"></path></g><g data-mml-node="mi" transform="translate(7075,0)"><path data-c="1D459" d="M117 59Q117 26 142 26Q179 26 205 131Q211 151 215 152Q217 153 225 153H229Q238 153 241 153T246 151T248 144Q247 138 245 128T234 90T214 43T183 6T137 -11Q101 -11 70 11T38 85Q38 97 39 102L104 360Q167 615 167 623Q167 626 166 628T162 632T157 634T149 635T141 636T132 637T122 637Q112 637 109 637T101 638T95 641T94 647Q94 649 96 661Q101 680 107 682T179 688Q194 689 213 690T243 693T254 694Q266 694 266 686Q266 675 193 386T118 83Q118 81 118 75T117 65V59Z"></path></g><g data-mml-node="TeXAtom" data-mjx-texclass="ORD" transform="translate(7373,0)"><g data-mml-node="mo"><path data-c="2F" d="M423 750Q432 750 438 744T444 730Q444 725 271 248T92 -240Q85 -250 75 -250Q68 -250 62 -245T56 -231Q56 -221 230 257T407 740Q411 750 423 750Z"></path></g></g><g data-mml-node="mi" transform="translate(7873,0)"><path data-c="1D43F" d="M228 637Q194 637 192 641Q191 643 191 649Q191 673 202 682Q204 683 217 683Q271 680 344 680Q485 680 506 683H518Q524 677 524 674T522 656Q517 641 513 637H475Q406 636 394 628Q387 624 380 600T313 336Q297 271 279 198T252 88L243 52Q243 48 252 48T311 46H328Q360 46 379 47T428 54T478 72T522 106T564 161Q580 191 594 228T611 270Q616 273 628 273H641Q647 264 647 262T627 203T583 83T557 9Q555 4 553 3T537 0T494 -1Q483 -1 418 -1T294 0H116Q32 0 32 10Q32 17 34 24Q39 43 44 45Q48 46 59 46H65Q92 46 125 49Q139 52 144 61Q147 65 216 339T285 628Q285 635 228 637Z"></path></g></g></g></svg></mjx-container></li> </ul> </li> -<li>异常情况:<ul> +<li>异常情况: +<ul> <li>升高: 如果伴随转氨酶升高,多见于黄疸型肝炎,或其他疾病造成的黄疸症状。如果没有伴随转氨酶升高,那么可能是先天性胆红素代谢异常或慢性溶血。</li> </ul> </li> @@ -4998,15 +5557,20 @@ await prisma.$transaction(async tx => { <p>肩袖损伤是由退行性病变或外力等导致肩袖的4块肌肉、肌腱发生病变,进而导致肩关节局部疼痛、活动受限的疾病。</p> <p>许多肩袖损伤患者无明确的外伤史,而是由长期做过顶运动、提重物或上肢长期固定于一个姿势引起的。</p> <ul> -<li><p>肩周炎的疼痛范围广,涉及整个肩关节,肩袖损伤引起的疼痛多出现在肩前方、外上方</p> +<li> +<p>肩周炎的疼痛范围广,涉及整个肩关节,肩袖损伤引起的疼痛多出现在肩前方、外上方</p> </li> -<li><p>肩周炎的压痛点多而广,肩袖损的伤压痛点多出现在肩前方、上方及肩胛骨外侧缘。</p> +<li> +<p>肩周炎的压痛点多而广,肩袖损的伤压痛点多出现在肩前方、上方及肩胛骨外侧缘。</p> </li> -<li><p>肩周炎患者对气候变化较为敏感,肩袖损伤患者对气候变化不敏感,对劳累、提重物及做过顶运动较为敏感。</p> +<li> +<p>肩周炎患者对气候变化较为敏感,肩袖损伤患者对气候变化不敏感,对劳累、提重物及做过顶运动较为敏感。</p> </li> -<li><p>肩周炎患者活动受限范围广,肩袖损伤患者多以肩关节外展活动受限为主,同时伴有外展无力。</p> +<li> +<p>肩周炎患者活动受限范围广,肩袖损伤患者多以肩关节外展活动受限为主,同时伴有外展无力。</p> </li> -<li><p>肩周炎患者进行上举过顶运动训练后活动范围会好转,症状会减轻;而肩袖损伤患者进行上举过顶运动训练后疼痛加重。</p> +<li> +<p>肩周炎患者进行上举过顶运动训练后活动范围会好转,症状会减轻;而肩袖损伤患者进行上举过顶运动训练后疼痛加重。</p> </li> </ul> ]]></content> @@ -5019,41 +5583,51 @@ await prisma.$transaction(async tx => { <title>肺功能检查数值</title> <url>/2025/03/20/%E8%82%BA%E5%8A%9F%E8%83%BD%E6%A3%80%E6%9F%A5%E6%95%B0%E5%80%BC/</url> <content><![CDATA[<p>肺功能测试是评估患者呼吸系统健康的重要工具。各个指标的及其异常数值可能指示的潜在生理疾病:</p> -<h3 id="1-FEV1(第一秒用力呼气量)"><a href="#1-FEV1(第一秒用力呼气量)" class="headerlink" title="1. FEV1(第一秒用力呼气量)"></a>1. FEV1(第一秒用力呼气量)</h3><ul> +<h3 id="1-FEV1(第一秒用力呼气量)"><a class="header-anchor" href="#1-FEV1(第一秒用力呼气量)">¶</a>1. FEV1(第一秒用力呼气量)</h3> +<ul> <li>评估:FEV1用于评估气道的通畅程度。它反映了在用力呼气的第一秒内,患者能够排出的气体量。</li> <li>异常:FEV1降低通常提示气道阻塞,常见于慢性阻塞性肺病(COPD)、哮喘、支气管炎等疾病。</li> </ul> -<h3 id="2-FVC(用力肺活量)"><a href="#2-FVC(用力肺活量)" class="headerlink" title="2. FVC(用力肺活量)"></a>2. FVC(用力肺活量)</h3><ul> +<h3 id="2-FVC(用力肺活量)"><a class="header-anchor" href="#2-FVC(用力肺活量)">¶</a>2. FVC(用力肺活量)</h3> +<ul> <li>评估:FVC测量的是患者在一次用力呼气中能够排出的最大气体量,反映了肺的容量和扩张能力。</li> <li>异常:FVC降低可能指示限制性肺病,如肺纤维化、胸廓畸形或神经肌肉疾病等。</li> </ul> -<h3 id="3-FEV1-FVC比值"><a href="#3-FEV1-FVC比值" class="headerlink" title="3. FEV1/FVC比值"></a>3. FEV1/FVC比值</h3><ul> -<li>评估:FEV1/FVC比值用于区分阻塞性和限制性肺病。正常情况下,该比值应大于70%。</li> -<li>异常:<ul> +<h3 id="3-FEV1-FVC比值"><a class="header-anchor" href="#3-FEV1-FVC比值">¶</a>3. FEV1/FVC比值</h3> +<ul> +<li>评估:FEV1/FVC比值用于区分阻塞性和限制性肺病。正常情况下,该比值应大于70%。</li> +<li>异常: +<ul> <li>低于70%:提示气道阻塞,常见于COPD和哮喘。</li> <li>正常或高于70%但FVC降低:可能提示限制性肺病。</li> </ul> </li> </ul> -<h3 id="4-PEF(峰值呼气流量)"><a href="#4-PEF(峰值呼气流量)" class="headerlink" title="4. PEF(峰值呼气流量)"></a>4. PEF(峰值呼气流量)</h3><ul> +<h3 id="4-PEF(峰值呼气流量)"><a class="header-anchor" href="#4-PEF(峰值呼气流量)">¶</a>4. PEF(峰值呼气流量)</h3> +<ul> <li>评估:PEF测量患者在用力呼气时达到的最大流速,常用于监测哮喘患者的病情变化。</li> <li>异常:PEF降低可能提示气道狭窄或阻塞,常见于哮喘急性发作或COPD加重。</li> </ul> -<h3 id="5-MVV(最大通气量)"><a href="#5-MVV(最大通气量)" class="headerlink" title="5. MVV(最大通气量)"></a>5. MVV(最大通气量)</h3><ul> +<h3 id="5-MVV(最大通气量)"><a class="header-anchor" href="#5-MVV(最大通气量)">¶</a>5. MVV(最大通气量)</h3> +<ul> <li>评估:MVV测量在一定时间内(通常是12秒)能够进行的最大通气量,反映了肺部的通气能力和呼吸肌的力量。</li> <li>异常:MVV降低可能与呼吸肌无力、气道阻塞或肺部疾病(如COPD)相关。</li> </ul> -<h3 id="6-TLC(总肺容量)"><a href="#6-TLC(总肺容量)" class="headerlink" title="6. TLC(总肺容量)"></a>6. TLC(总肺容量)</h3><ul> +<h3 id="6-TLC(总肺容量)"><a class="header-anchor" href="#6-TLC(总肺容量)">¶</a>6. TLC(总肺容量)</h3> +<ul> <li>评估:TLC测量肺部在最大吸气后所能容纳的气体总量,反映了肺的整体容量。</li> -<li>异常:<ul> +<li>异常: +<ul> <li>增加:可能与阻塞性肺病(如COPD)相关,因肺部过度膨胀。</li> <li>降低:可能与限制性肺病(如肺纤维化、胸廓畸形)相关。</li> </ul> </li> </ul> -<h3 id="7-RV(残气量)"><a href="#7-RV(残气量)" class="headerlink" title="7. RV(残气量)"></a>7. RV(残气量)</h3><ul> +<h3 id="7-RV(残气量)"><a class="header-anchor" href="#7-RV(残气量)">¶</a>7. RV(残气量)</h3> +<ul> <li>评估:RV测量在最大呼气后,肺内仍然残留的气体量。</li> -<li>异常:<ul> +<li>异常: +<ul> <li>增加:常见于阻塞性肺病,因气道阻塞导致气体无法完全排出。</li> <li>降低:可能与限制性肺病相关。</li> </ul> @@ -5068,60 +5642,70 @@ await prisma.$transaction(async tx => { <title>肺炎支原体注意事项</title> <url>/2023/10/25/%E8%82%BA%E7%82%8E%E6%94%AF%E5%8E%9F%E4%BD%93%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B9/</url> <content><![CDATA[<ol> -<li>什么是肺炎支原体<ul> +<li>什么是肺炎支原体 +<ul> <li>大小介于细菌和病毒之间的病原微生物, 缺乏细胞壁, 对作用于细胞壁的抗菌药物 (例如青霉素和头孢) 有耐药性</li> <li>感染不分季节的, 不过一般是北方地区秋冬季流行, 南方地区夏秋季流行</li> <li>一般多见于五岁以上的儿童, 但五岁以下也可能感染并发病</li> </ul> </li> -<li>肺炎支原体如何传播<ul> +<li>肺炎支原体如何传播 +<ul> <li>主要通过飞沫和直接接触传播</li> <li>潜伏期为一到三周</li> <li>从潜伏期到症状缓解均有传染性</li> </ul> </li> -<li>肺炎支原体感染有何症状表现<ul> +<li>肺炎支原体感染有何症状表现 +<ul> <li>主要临床表现为发热, 咳嗽, 头痛, 流涕, 咽痛, 耳痛等</li> <li>轻者可能无症状或是上呼吸道感染</li> <li>重者可能导致肺炎, 肺实变, 胸腔积液, 坏死性肺炎</li> </ul> </li> -<li>成年人是否也会感染肺炎支原体<ul> +<li>成年人是否也会感染肺炎支原体 +<ul> <li>长时间和肺炎支原体感染的患者相处很有可能会被感染</li> <li>如果出现发热, 剧烈咳嗽, 甚至有肺部表现, 要及时去医院</li> </ul> </li> -<li>如何分辨肺炎支原体感染和普通感冒<ul> +<li>如何分辨肺炎支原体感染和普通感冒 +<ul> <li>初期感染上呼吸道时, 存在和普通感染类似的症状, 例如鼻塞咽痛发热等</li> <li>可以通过血清抗体检测, 核酸检测等检出</li> <li>医生可以通过根据患者的病史, 症状和体征结合相关的常规化检查来综合判断</li> <li>常人可以通过判断咳嗽情况判断: 一般会出现阵发性, 成串的咳嗽, 早期是干咳, 咳嗽比较剧烈. 或有发热持续不退, 咳嗽加重等情况</li> </ul> </li> -<li>治疗肺炎支原体的常用药物<ul> +<li>治疗肺炎支原体的常用药物 +<ul> <li>最佳的治疗窗口期为发热后五到十天之内</li> <li>一线治疗药物以大环内酯类抗生素为主, 比如阿奇霉素, 红霉素, 克拉霉素</li> <li>对于耐大环内酯类抗菌药物的患者要考虑其他药物</li> <li>如果感染比较严重, 重症支原体感染, 则需要综合治疗, 比如糖皮质激素以及支气管镜介入治疗</li> </ul> </li> -<li>如何判断是否需要住院治疗<ul> +<li>如何判断是否需要住院治疗 +<ul> <li>轻症经过大环内酯类药物一般均能控制病情, 但体温正常之后咳嗽可能还会持续两周左右, 胸片肺炎阴影基本均可吸收</li> <li>重症需要住院, 重症可能会有混合病毒或者细菌感染, 要加用相应的药物治疗</li> </ul> </li> -<li>耐药和不耐药患者的治疗差异<ul> +<li>耐药和不耐药患者的治疗差异 +<ul> <li>并无太大差异, 主要是耐药患者退烧时间会更长, 换言之病程较长</li> </ul> </li> -<li>支原体肺炎是否会引发白肺<ul> +<li>支原体肺炎是否会引发白肺 +<ul> <li>可能会, 但是跟双肺弥漫性病变的白肺是两个概念</li> <li>通过拍背排痰, 药物祛痰, 支气管镜治疗等手段, 患者可以在较短的时间内痊愈, 基本不会引发生命危险</li> <li>重症及难治性肺炎支原体感染患者可能会遗留肺结构或功能损害</li> </ul> </li> </ol> -<h2 id="支原体肺炎-流感-新冠肺炎的区别"><a href="#支原体肺炎-流感-新冠肺炎的区别" class="headerlink" title="支原体肺炎, 流感, 新冠肺炎的区别"></a>支原体肺炎, 流感, 新冠肺炎的区别</h2><table> +<h2 id="支原体肺炎-流感-新冠肺炎的区别"><a class="header-anchor" href="#支原体肺炎-流感-新冠肺炎的区别">¶</a>支原体肺炎, 流感, 新冠肺炎的区别</h2> +<table> <thead> <tr> <th>区别</th> @@ -5130,7 +5714,8 @@ await prisma.$transaction(async tx => { <th>新冠肺炎</th> </tr> </thead> -<tbody><tr> +<tbody> +<tr> <td>致病菌</td> <td>肺炎支原体</td> <td>流感病毒</td> @@ -5178,7 +5763,8 @@ await prisma.$transaction(async tx => { <td>有一定自限性, 一般一周内好转</td> <td>一般7~14天可好转</td> </tr> -</tbody></table> +</tbody> +</table> ]]></content> <tags> <tag>Medicine</tag> @@ -5199,19 +5785,21 @@ await prisma.$transaction(async tx => { <entry> <title>螺内酯片</title> <url>/2023/03/14/%E8%9E%BA%E5%86%85%E9%85%AF%E7%89%87/</url> - <content><![CDATA[<h2 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h2><p>螺内酯是保钾利尿药,用于治疗心衰、低钾血症和高血压等。但是,它也会阻断雄激素受体,从而具有抗雄激素特性(我想你应该联想到了什么);不过其效力较弱,需服用较大剂量方可充分起效(尿频等副作用也更明显)。</p> + <content><![CDATA[<h2 id="简介"><a class="header-anchor" href="#简介">¶</a>简介</h2> +<p>螺内酯是保钾利尿药,用于治疗心衰、低钾血症和高血压等。但是,它也会阻断雄激素受体,从而具有抗雄激素特性(我想你应该联想到了什么);不过其效力较弱,需服用较大剂量方可充分起效(尿频等副作用也更明显)。</p> <p>英文名称:Spironolactone Tablets.</p> <p>需要注意的是,开始服用螺内酯前:</p> <ol> -<li>血清钾应小于 5.0mmol/L</li> +<li>血清钾应小于 5.0mmol/L</li> <li>肾功能应正常,服用螺内酯后定期监测血钾和肌酐</li> <li>避免过多食用富钾食品,如香蕉、海带、含钾代用盐等</li> <li>不得同时服用其它利钾药物; 多喝水。</li> </ol> -<p>对于利尿方面,螺内酯的利尿作用不强,起效慢而维时久,其利尿作用与体内醛固酮的浓度有关。仅当体内有醛固酮存在时,它才发挥作用。对切除肾上腺的动物则无利尿作用。由于其利尿作用较弱,抑制Na+再吸收量还不到3%,因此较少单用。常与噻嗪类利尿药或高效利尿药合用以增强利尿效果并减少K+的丧失。 </p> +<p>对于利尿方面,螺内酯的利尿作用不强,起效慢而维时久,其利尿作用与体内醛固酮的浓度有关。仅当体内有醛固酮存在时,它才发挥作用。对切除肾上腺的动物则无利尿作用。由于其利尿作用较弱,抑制Na+再吸收量还不到3%,因此较少单用。常与噻嗪类利尿药或高效利尿药合用以增强利尿效果并减少K+的丧失。</p> <p>如果病人出现了高钾血症,那应该立即停药。另外如果在进食的时候或者餐后用药,可以减少胃肠道反应(提高生物利用度)。</p> <p><strong>本药起作用较慢,而维持时间较长,故首日剂量可增加至常规剂量的2-3倍,以后酌情调整剂量。与其他利尿药合用时,可先于其他利尿药2-3日服用。在已应用其他利尿药再加用本药时,其他利尿药剂量在最初2-3日可减量50%,以后酌情调整剂量。在停药时,本药应先于其他利尿药2-3日停药。</strong></p> -<h2 id="副作用"><a href="#副作用" class="headerlink" title="副作用:"></a>副作用:</h2><ol> +<h2 id="副作用"><a class="header-anchor" href="#副作用">¶</a>副作用:</h2> +<ol> <li>高钾血症:螺内酯最严重的副作用,可导致住院甚至死亡。(高年龄(超 45 岁)、肾功能不全、与其它利钾药物合用、钾补剂的服用等)</li> <li>尿频</li> <li>血压过低</li> @@ -5223,34 +5811,39 @@ await prisma.$transaction(async tx => { <li>皮质醇水平升高</li> <li>胃肠道反应,包括恶心、呕吐、腹泻、胃痉挛、胃炎等</li> </ol> -<h2 id="药理"><a href="#药理" class="headerlink" title="药理"></a>药理</h2><p>本药结构与醛固酮相似,为醛固酮的竞争性抑制剂。作用于远曲小管和集合管,阻断Na+-K+和Na+-H+交换,结果Na+、C1-和水排泄增多,K+、Mg2+和H+排泄减少,对Ca2+和P3-的作用不定。由于本药仅作用于远曲小管和集合管,对肾小管其他各段无作用,故利尿作用较弱。另外,本药对肾小管以外的醛固酮靶器官也有作用。</p> -<h2 id="代谢"><a href="#代谢" class="headerlink" title="代谢"></a>代谢</h2><p>这个药口服吸收较好,生物利用度大于90%,血浆蛋白结合率在90%以上,进入体内后80%由肝脏迅速代谢为有活性的坎利酮(canrenone),口服1日左右起效,2-3日达高峰,停药后作用仍可维持2-3日。依服药方式不同T1/2有所差异,每日服药1~2次时平均19小时(13-24小时),每日服药4次时缩短为12.5小时(9-16小时)。无活性代谢产物从肾脏和胆道排泄,约有10%以原形从肾脏排泄。 </p> -<h2 id="适应症"><a href="#适应症" class="headerlink" title="适应症"></a>适应症</h2><ol> +<h2 id="药理"><a class="header-anchor" href="#药理">¶</a>药理</h2> +<p>本药结构与醛固酮相似,为醛固酮的竞争性抑制剂。作用于远曲小管和集合管,阻断Na+-K+和Na+-H+交换,结果Na+、C1-和水排泄增多,K+、Mg2+和H+排泄减少,对Ca2+和P3-的作用不定。由于本药仅作用于远曲小管和集合管,对肾小管其他各段无作用,故利尿作用较弱。另外,本药对肾小管以外的醛固酮靶器官也有作用。</p> +<h2 id="代谢"><a class="header-anchor" href="#代谢">¶</a>代谢</h2> +<p>这个药口服吸收较好,生物利用度大于90%,血浆蛋白结合率在90%以上,进入体内后80%由肝脏迅速代谢为有活性的坎利酮(canrenone),口服1日左右起效,2-3日达高峰,停药后作用仍可维持2-3日。依服药方式不同T1/2有所差异,每日服药1~2次时平均19小时(13-24小时),每日服药4次时缩短为12.5小时(9-16小时)。无活性代谢产物从肾脏和胆道排泄,约有10%以原形从肾脏排泄。</p> +<h2 id="适应症"><a class="header-anchor" href="#适应症">¶</a>适应症</h2> +<ol> <li>水肿性疾病 与其他利尿药合用,治疗充血性水肿、肝硬化腹水、肾性水肿等水肿性疾病,其目的在于纠正上述疾病时伴发的继发性醛固酮分泌增多,并对抗其他利尿药的排钾作用。也用于特发性水肿的治疗。</li> <li>高血压 作为治疗高血压的辅助药物。</li> <li>原发性醛固酮增多症 螺内酯可用于此病的诊断和治疗。</li> <li>低钾血症的预防 与噻嗪类利尿药合用,增强利尿效应和预防低钾血症。</li> </ol> -<p> </p> -<h2 id="药物相互作用"><a href="#药物相互作用" class="headerlink" title="药物相互作用"></a>药物相互作用</h2><ol> +<h2 id="药物相互作用"><a class="header-anchor" href="#药物相互作用">¶</a>药物相互作用</h2> +<ol> <li>肾上腺皮质激素尤其是具有较强盐皮质激素作用者,促肾上腺皮质激素能减弱本药的利尿作用,而拮抗本药的潴钾作用。</li> <li>雌激素能引起水钠潴留,从而减弱本药的利尿作用。</li> <li>非甾体类消炎镇痛药,尤其是吲哚美辛,能降低本药的利尿作用,且合用时肾毒性增加。</li> <li>拟交感神经药物降低本药的降压作用。</li> <li>多巴胺加强本药的利尿作用。</li> <li>与引起血压下降的药物合用,利尿和降压效果均加强。</li> -<li>与下列药物合用时,发生高钾血症的机会增加,如含钾药物、库存血(含钾30mmol/L,如库存10日以上含钾高达65mmol/L)、血管紧张素转换酶抑制剂、血管紧张素Ⅱ受体拮抗剂和环孢素A等。</li> +<li>与下列药物合用时,发生高钾血症的机会增加,如含钾药物、库存血(含钾30mmol/L,如库存10日以上含钾高达65mmol/L)、血管紧张素转换酶抑制剂、血管紧张素Ⅱ受体拮抗剂和环孢素A等。</li> <li>与葡萄糖胰岛素液、碱剂、钠型降钾交换树脂合用,发生高钾血症的机会减少。</li> <li>本药使地高辛半衰期延长。</li> <li>与氯化铵合用易发生代谢性酸中毒。</li> <li>与肾毒性药物合用,肾毒性增加。</li> <li>甘珀酸钠、甘草类制剂具有醛固酮样作用,可降低本药的利尿作用。</li> </ol> -<h2 id="其他"><a href="#其他" class="headerlink" title="其他"></a>其他</h2><p>螺内酯为《2018版中国国家基本药物目录》在列药物,“基本药物”指的是能够满足基本医疗卫生需求,剂型适宜、保证供应、基层能够配备、国民能够公平获得的药品。</p> -<h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><ul> +<h2 id="其他"><a class="header-anchor" href="#其他">¶</a>其他</h2> +<p>螺内酯为《2018版中国国家基本药物目录》在列药物,“基本药物”指的是能够满足基本医疗卫生需求,剂型适宜、保证供应、基层能够配备、国民能够公平获得的药品。</p> +<h2 id="参考"><a class="header-anchor" href="#参考">¶</a>参考</h2> +<ul> <li><a href="https://mtf.wiki/zh-cn/docs/medicine/antiandrogen/spironolactone/">https://mtf.wiki/zh-cn/docs/medicine/antiandrogen/spironolactone/</a></li> -<li><a href="https://www.yixue.com/%E8%9E%BA%E5%86%85%E9%85%AF">https://www.yixue.com/%E8%9E%BA%E5%86%85%E9%85%AF</a></li> -<li><a href="https://www.yixue.com/%E8%8D%AF%E7%90%86%E5%AD%A6/%E8%9E%BA%E5%86%85%E9%85%AF">https://www.yixue.com/%E8%8D%AF%E7%90%86%E5%AD%A6/%E8%9E%BA%E5%86%85%E9%85%AF</a></li> +<li><a href="https://www.yixue.com/%E8%9E%BA%E5%86%85%E9%85%AF">https://www.yixue.com/螺内酯</a></li> +<li><a href="https://www.yixue.com/%E8%8D%AF%E7%90%86%E5%AD%A6/%E8%9E%BA%E5%86%85%E9%85%AF">https://www.yixue.com/药理学/螺内酯</a></li> </ul> ]]></content> <tags> @@ -5263,29 +5856,38 @@ await prisma.$transaction(async tx => { <content><![CDATA[<p>这里我给出一些常见的值,更详细的听医生说哦,我们以下图为例:</p> <p><img src="/img/%E5%8C%BB%E5%AD%A6/%E8%A1%80%E5%B8%B8%E8%A7%84%E5%8C%96%E9%AA%8C%E5%8D%95Demo.jpeg" alt="血常规化验单Demo"></p> <ul> -<li>红细胞 (RBC)<ul> +<li>红细胞 (RBC) +<ul> <li>正常情况: 男性 <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.566ex;" xmlns="http://www.w3.org/2000/svg" width="20.587ex" height="2.52ex" role="img" focusable="false" viewBox="0 -864 9099.6 1114"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="mo"><path data-c="28" d="M94 250Q94 319 104 381T127 488T164 576T202 643T244 695T277 729T302 750H315H319Q333 750 333 741Q333 738 316 720T275 667T226 581T184 443T167 250T184 58T225 -81T274 -167T316 -220T333 -241Q333 -250 318 -250H315H302L274 -226Q180 -141 137 -14T94 250Z"></path></g><g data-mml-node="mn" transform="translate(389,0)"><path data-c="34" d="M462 0Q444 3 333 3Q217 3 199 0H190V46H221Q241 46 248 46T265 48T279 53T286 61Q287 63 287 115V165H28V211L179 442Q332 674 334 675Q336 677 355 677H373L379 671V211H471V165H379V114Q379 73 379 66T385 54Q393 47 442 46H471V0H462ZM293 211V545L74 212L183 211H293Z"></path><path data-c="2E" d="M78 60Q78 84 95 102T138 120Q162 120 180 104T199 61Q199 36 182 18T139 0T96 17T78 60Z" transform="translate(500,0)"></path><path data-c="37" d="M55 458Q56 460 72 567L88 674Q88 676 108 676H128V672Q128 662 143 655T195 646T364 644H485V605L417 512Q408 500 387 472T360 435T339 403T319 367T305 330T292 284T284 230T278 162T275 80Q275 66 275 52T274 28V19Q270 2 255 -10T221 -22Q210 -22 200 -19T179 0T168 40Q168 198 265 368Q285 400 349 489L395 552H302Q128 552 119 546Q113 543 108 522T98 479L95 458V455H55V458Z" transform="translate(778,0)"></path><path data-c="35" d="M164 157Q164 133 148 117T109 101H102Q148 22 224 22Q294 22 326 82Q345 115 345 210Q345 313 318 349Q292 382 260 382H254Q176 382 136 314Q132 307 129 306T114 304Q97 304 95 310Q93 314 93 485V614Q93 664 98 664Q100 666 102 666Q103 666 123 658T178 642T253 634Q324 634 389 662Q397 666 402 666Q410 666 410 648V635Q328 538 205 538Q174 538 149 544L139 546V374Q158 388 169 396T205 412T256 420Q337 420 393 355T449 201Q449 109 385 44T229 -22Q148 -22 99 32T50 154Q50 178 61 192T84 210T107 214Q132 214 148 197T164 157Z" transform="translate(1278,0)"></path></g><g data-mml-node="mo" transform="translate(2389.2,0)"><path data-c="B1" d="M56 320T56 333T70 353H369V502Q369 651 371 655Q376 666 388 666Q402 666 405 654T409 596V500V353H707Q722 345 722 333Q722 320 707 313H409V40H707Q722 32 722 20T707 0H70Q56 7 56 20T70 40H369V313H70Q56 320 56 333Z"></path></g><g data-mml-node="mn" transform="translate(3389.4,0)"><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z"></path><path data-c="2E" d="M78 60Q78 84 95 102T138 120Q162 120 180 104T199 61Q199 36 182 18T139 0T96 17T78 60Z" transform="translate(500,0)"></path><path data-c="37" d="M55 458Q56 460 72 567L88 674Q88 676 108 676H128V672Q128 662 143 655T195 646T364 644H485V605L417 512Q408 500 387 472T360 435T339 403T319 367T305 330T292 284T284 230T278 162T275 80Q275 66 275 52T274 28V19Q270 2 255 -10T221 -22Q210 -22 200 -19T179 0T168 40Q168 198 265 368Q285 400 349 489L395 552H302Q128 552 119 546Q113 543 108 522T98 479L95 458V455H55V458Z" transform="translate(778,0)"></path><path data-c="35" d="M164 157Q164 133 148 117T109 101H102Q148 22 224 22Q294 22 326 82Q345 115 345 210Q345 313 318 349Q292 382 260 382H254Q176 382 136 314Q132 307 129 306T114 304Q97 304 95 310Q93 314 93 485V614Q93 664 98 664Q100 666 102 666Q103 666 123 658T178 642T253 634Q324 634 389 662Q397 666 402 666Q410 666 410 648V635Q328 538 205 538Q174 538 149 544L139 546V374Q158 388 169 396T205 412T256 420Q337 420 393 355T449 201Q449 109 385 44T229 -22Q148 -22 99 32T50 154Q50 178 61 192T84 210T107 214Q132 214 148 197T164 157Z" transform="translate(1278,0)"></path></g><g data-mml-node="mo" transform="translate(5167.4,0)"><path data-c="29" d="M60 749L64 750Q69 750 74 750H86L114 726Q208 641 251 514T294 250Q294 182 284 119T261 12T224 -76T186 -143T145 -194T113 -227T90 -246Q87 -249 86 -250H74Q66 -250 63 -250T58 -247T55 -238Q56 -237 66 -225Q221 -64 221 250T66 725Q56 737 55 738Q55 746 60 749Z"></path></g><g data-mml-node="mi" transform="translate(5556.4,0)"><path data-c="1D465" d="M52 289Q59 331 106 386T222 442Q257 442 286 424T329 379Q371 442 430 442Q467 442 494 420T522 361Q522 332 508 314T481 292T458 288Q439 288 427 299T415 328Q415 374 465 391Q454 404 425 404Q412 404 406 402Q368 386 350 336Q290 115 290 78Q290 50 306 38T341 26Q378 26 414 59T463 140Q466 150 469 151T485 153H489Q504 153 504 145Q504 144 502 134Q486 77 440 33T333 -11Q263 -11 227 52Q186 -10 133 -10H127Q78 -10 57 16T35 71Q35 103 54 123T99 143Q142 143 142 101Q142 81 130 66T107 46T94 41L91 40Q91 39 97 36T113 29T132 26Q168 26 194 71Q203 87 217 139T245 247T261 313Q266 340 266 352Q266 380 251 392T217 404Q177 404 142 372T93 290Q91 281 88 280T72 278H58Q52 284 52 289Z"></path></g><g data-mml-node="msup" transform="translate(6128.4,0)"><g data-mml-node="mn"><path data-c="31" d="M213 578L200 573Q186 568 160 563T102 556H83V602H102Q149 604 189 617T245 641T273 663Q275 666 285 666Q294 666 302 660V361L303 61Q310 54 315 52T339 48T401 46H427V0H416Q395 3 257 3Q121 3 100 0H88V46H114Q136 46 152 46T177 47T193 50T201 52T207 57T213 61V578Z"></path><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z" transform="translate(500,0)"></path></g><g data-mml-node="TeXAtom" transform="translate(1033,393.1) scale(0.707)" data-mjx-texclass="ORD"><g data-mml-node="mn"><path data-c="31" d="M213 578L200 573Q186 568 160 563T102 556H83V602H102Q149 604 189 617T245 641T273 663Q275 666 285 666Q294 666 302 660V361L303 61Q310 54 315 52T339 48T401 46H427V0H416Q395 3 257 3Q121 3 100 0H88V46H114Q136 46 152 46T177 47T193 50T201 52T207 57T213 61V578Z"></path><path data-c="32" d="M109 429Q82 429 66 447T50 491Q50 562 103 614T235 666Q326 666 387 610T449 465Q449 422 429 383T381 315T301 241Q265 210 201 149L142 93L218 92Q375 92 385 97Q392 99 409 186V189H449V186Q448 183 436 95T421 3V0H50V19V31Q50 38 56 46T86 81Q115 113 136 137Q145 147 170 174T204 211T233 244T261 278T284 308T305 340T320 369T333 401T340 431T343 464Q343 527 309 573T212 619Q179 619 154 602T119 569T109 550Q109 549 114 549Q132 549 151 535T170 489Q170 464 154 447T109 429Z" transform="translate(500,0)"></path></g></g></g><g data-mml-node="TeXAtom" data-mjx-texclass="ORD" transform="translate(7918.6,0)"><g data-mml-node="mo"><path data-c="2F" d="M423 750Q432 750 438 744T444 730Q444 725 271 248T92 -240Q85 -250 75 -250Q68 -250 62 -245T56 -231Q56 -221 230 257T407 740Q411 750 423 750Z"></path></g></g><g data-mml-node="mi" transform="translate(8418.6,0)"><path data-c="1D43F" d="M228 637Q194 637 192 641Q191 643 191 649Q191 673 202 682Q204 683 217 683Q271 680 344 680Q485 680 506 683H518Q524 677 524 674T522 656Q517 641 513 637H475Q406 636 394 628Q387 624 380 600T313 336Q297 271 279 198T252 88L243 52Q243 48 252 48T311 46H328Q360 46 379 47T428 54T478 72T522 106T564 161Q580 191 594 228T611 270Q616 273 628 273H641Q647 264 647 262T627 203T583 83T557 9Q555 4 553 3T537 0T494 -1Q483 -1 418 -1T294 0H116Q32 0 32 10Q32 17 34 24Q39 43 44 45Q48 46 59 46H65Q92 46 125 49Q139 52 144 61Q147 65 216 339T285 628Q285 635 228 637Z"></path></g></g></g></svg></mjx-container> , 女性 <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.566ex;" xmlns="http://www.w3.org/2000/svg" width="20.587ex" height="2.52ex" role="img" focusable="false" viewBox="0 -864 9099.6 1114"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="mo"><path data-c="28" d="M94 250Q94 319 104 381T127 488T164 576T202 643T244 695T277 729T302 750H315H319Q333 750 333 741Q333 738 316 720T275 667T226 581T184 443T167 250T184 58T225 -81T274 -167T316 -220T333 -241Q333 -250 318 -250H315H302L274 -226Q180 -141 137 -14T94 250Z"></path></g><g data-mml-node="mn" transform="translate(389,0)"><path data-c="34" d="M462 0Q444 3 333 3Q217 3 199 0H190V46H221Q241 46 248 46T265 48T279 53T286 61Q287 63 287 115V165H28V211L179 442Q332 674 334 675Q336 677 355 677H373L379 671V211H471V165H379V114Q379 73 379 66T385 54Q393 47 442 46H471V0H462ZM293 211V545L74 212L183 211H293Z"></path><path data-c="2E" d="M78 60Q78 84 95 102T138 120Q162 120 180 104T199 61Q199 36 182 18T139 0T96 17T78 60Z" transform="translate(500,0)"></path><path data-c="32" d="M109 429Q82 429 66 447T50 491Q50 562 103 614T235 666Q326 666 387 610T449 465Q449 422 429 383T381 315T301 241Q265 210 201 149L142 93L218 92Q375 92 385 97Q392 99 409 186V189H449V186Q448 183 436 95T421 3V0H50V19V31Q50 38 56 46T86 81Q115 113 136 137Q145 147 170 174T204 211T233 244T261 278T284 308T305 340T320 369T333 401T340 431T343 464Q343 527 309 573T212 619Q179 619 154 602T119 569T109 550Q109 549 114 549Q132 549 151 535T170 489Q170 464 154 447T109 429Z" transform="translate(778,0)"></path><path data-c="35" d="M164 157Q164 133 148 117T109 101H102Q148 22 224 22Q294 22 326 82Q345 115 345 210Q345 313 318 349Q292 382 260 382H254Q176 382 136 314Q132 307 129 306T114 304Q97 304 95 310Q93 314 93 485V614Q93 664 98 664Q100 666 102 666Q103 666 123 658T178 642T253 634Q324 634 389 662Q397 666 402 666Q410 666 410 648V635Q328 538 205 538Q174 538 149 544L139 546V374Q158 388 169 396T205 412T256 420Q337 420 393 355T449 201Q449 109 385 44T229 -22Q148 -22 99 32T50 154Q50 178 61 192T84 210T107 214Q132 214 148 197T164 157Z" transform="translate(1278,0)"></path></g><g data-mml-node="mo" transform="translate(2389.2,0)"><path data-c="B1" d="M56 320T56 333T70 353H369V502Q369 651 371 655Q376 666 388 666Q402 666 405 654T409 596V500V353H707Q722 345 722 333Q722 320 707 313H409V40H707Q722 32 722 20T707 0H70Q56 7 56 20T70 40H369V313H70Q56 320 56 333Z"></path></g><g data-mml-node="mn" transform="translate(3389.4,0)"><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z"></path><path data-c="2E" d="M78 60Q78 84 95 102T138 120Q162 120 180 104T199 61Q199 36 182 18T139 0T96 17T78 60Z" transform="translate(500,0)"></path><path data-c="37" d="M55 458Q56 460 72 567L88 674Q88 676 108 676H128V672Q128 662 143 655T195 646T364 644H485V605L417 512Q408 500 387 472T360 435T339 403T319 367T305 330T292 284T284 230T278 162T275 80Q275 66 275 52T274 28V19Q270 2 255 -10T221 -22Q210 -22 200 -19T179 0T168 40Q168 198 265 368Q285 400 349 489L395 552H302Q128 552 119 546Q113 543 108 522T98 479L95 458V455H55V458Z" transform="translate(778,0)"></path><path data-c="35" d="M164 157Q164 133 148 117T109 101H102Q148 22 224 22Q294 22 326 82Q345 115 345 210Q345 313 318 349Q292 382 260 382H254Q176 382 136 314Q132 307 129 306T114 304Q97 304 95 310Q93 314 93 485V614Q93 664 98 664Q100 666 102 666Q103 666 123 658T178 642T253 634Q324 634 389 662Q397 666 402 666Q410 666 410 648V635Q328 538 205 538Q174 538 149 544L139 546V374Q158 388 169 396T205 412T256 420Q337 420 393 355T449 201Q449 109 385 44T229 -22Q148 -22 99 32T50 154Q50 178 61 192T84 210T107 214Q132 214 148 197T164 157Z" transform="translate(1278,0)"></path></g><g data-mml-node="mo" transform="translate(5167.4,0)"><path data-c="29" d="M60 749L64 750Q69 750 74 750H86L114 726Q208 641 251 514T294 250Q294 182 284 119T261 12T224 -76T186 -143T145 -194T113 -227T90 -246Q87 -249 86 -250H74Q66 -250 63 -250T58 -247T55 -238Q56 -237 66 -225Q221 -64 221 250T66 725Q56 737 55 738Q55 746 60 749Z"></path></g><g data-mml-node="mi" transform="translate(5556.4,0)"><path data-c="1D465" d="M52 289Q59 331 106 386T222 442Q257 442 286 424T329 379Q371 442 430 442Q467 442 494 420T522 361Q522 332 508 314T481 292T458 288Q439 288 427 299T415 328Q415 374 465 391Q454 404 425 404Q412 404 406 402Q368 386 350 336Q290 115 290 78Q290 50 306 38T341 26Q378 26 414 59T463 140Q466 150 469 151T485 153H489Q504 153 504 145Q504 144 502 134Q486 77 440 33T333 -11Q263 -11 227 52Q186 -10 133 -10H127Q78 -10 57 16T35 71Q35 103 54 123T99 143Q142 143 142 101Q142 81 130 66T107 46T94 41L91 40Q91 39 97 36T113 29T132 26Q168 26 194 71Q203 87 217 139T245 247T261 313Q266 340 266 352Q266 380 251 392T217 404Q177 404 142 372T93 290Q91 281 88 280T72 278H58Q52 284 52 289Z"></path></g><g data-mml-node="msup" transform="translate(6128.4,0)"><g data-mml-node="mn"><path data-c="31" d="M213 578L200 573Q186 568 160 563T102 556H83V602H102Q149 604 189 617T245 641T273 663Q275 666 285 666Q294 666 302 660V361L303 61Q310 54 315 52T339 48T401 46H427V0H416Q395 3 257 3Q121 3 100 0H88V46H114Q136 46 152 46T177 47T193 50T201 52T207 57T213 61V578Z"></path><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z" transform="translate(500,0)"></path></g><g data-mml-node="TeXAtom" transform="translate(1033,393.1) scale(0.707)" data-mjx-texclass="ORD"><g data-mml-node="mn"><path data-c="31" d="M213 578L200 573Q186 568 160 563T102 556H83V602H102Q149 604 189 617T245 641T273 663Q275 666 285 666Q294 666 302 660V361L303 61Q310 54 315 52T339 48T401 46H427V0H416Q395 3 257 3Q121 3 100 0H88V46H114Q136 46 152 46T177 47T193 50T201 52T207 57T213 61V578Z"></path><path data-c="32" d="M109 429Q82 429 66 447T50 491Q50 562 103 614T235 666Q326 666 387 610T449 465Q449 422 429 383T381 315T301 241Q265 210 201 149L142 93L218 92Q375 92 385 97Q392 99 409 186V189H449V186Q448 183 436 95T421 3V0H50V19V31Q50 38 56 46T86 81Q115 113 136 137Q145 147 170 174T204 211T233 244T261 278T284 308T305 340T320 369T333 401T340 431T343 464Q343 527 309 573T212 619Q179 619 154 602T119 569T109 550Q109 549 114 549Q132 549 151 535T170 489Q170 464 154 447T109 429Z" transform="translate(500,0)"></path></g></g></g><g data-mml-node="TeXAtom" data-mjx-texclass="ORD" transform="translate(7918.6,0)"><g data-mml-node="mo"><path data-c="2F" d="M423 750Q432 750 438 744T444 730Q444 725 271 248T92 -240Q85 -250 75 -250Q68 -250 62 -245T56 -231Q56 -221 230 257T407 740Q411 750 423 750Z"></path></g></g><g data-mml-node="mi" transform="translate(8418.6,0)"><path data-c="1D43F" d="M228 637Q194 637 192 641Q191 643 191 649Q191 673 202 682Q204 683 217 683Q271 680 344 680Q485 680 506 683H518Q524 677 524 674T522 656Q517 641 513 637H475Q406 636 394 628Q387 624 380 600T313 336Q297 271 279 198T252 88L243 52Q243 48 252 48T311 46H328Q360 46 379 47T428 54T478 72T522 106T564 161Q580 191 594 228T611 270Q616 273 628 273H641Q647 264 647 262T627 203T583 83T557 9Q555 4 553 3T537 0T494 -1Q483 -1 418 -1T294 0H116Q32 0 32 10Q32 17 34 24Q39 43 44 45Q48 46 59 46H65Q92 46 125 49Q139 52 144 61Q147 65 216 339T285 628Q285 635 228 637Z"></path></g></g></g></svg></mjx-container></li> -<li>异常情况:<ol> +<li>异常情况: +<ol> <li>升高: 真性红细胞增多症, 严重脱水, 肺源性心脏病, 先天性心脏病, 高山地区的居民和严重烧伤等</li> <li>降低: 贫血</li> </ol> </li> </ul> </li> -<li>血红蛋白 (HGB)<ul> +<li>血红蛋白 (HGB) +<ul> <li>正常情况: 男性 <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.566ex;" xmlns="http://www.w3.org/2000/svg" width="13.933ex" height="2.262ex" role="img" focusable="false" viewBox="0 -750 6158.4 1000"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="mo"><path data-c="28" d="M94 250Q94 319 104 381T127 488T164 576T202 643T244 695T277 729T302 750H315H319Q333 750 333 741Q333 738 316 720T275 667T226 581T184 443T167 250T184 58T225 -81T274 -167T316 -220T333 -241Q333 -250 318 -250H315H302L274 -226Q180 -141 137 -14T94 250Z"></path></g><g data-mml-node="mn" transform="translate(389,0)"><path data-c="31" d="M213 578L200 573Q186 568 160 563T102 556H83V602H102Q149 604 189 617T245 641T273 663Q275 666 285 666Q294 666 302 660V361L303 61Q310 54 315 52T339 48T401 46H427V0H416Q395 3 257 3Q121 3 100 0H88V46H114Q136 46 152 46T177 47T193 50T201 52T207 57T213 61V578Z"></path><path data-c="34" d="M462 0Q444 3 333 3Q217 3 199 0H190V46H221Q241 46 248 46T265 48T279 53T286 61Q287 63 287 115V165H28V211L179 442Q332 674 334 675Q336 677 355 677H373L379 671V211H471V165H379V114Q379 73 379 66T385 54Q393 47 442 46H471V0H462ZM293 211V545L74 212L183 211H293Z" transform="translate(500,0)"></path><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z" transform="translate(1000,0)"></path></g><g data-mml-node="mo" transform="translate(2111.2,0)"><path data-c="B1" d="M56 320T56 333T70 353H369V502Q369 651 371 655Q376 666 388 666Q402 666 405 654T409 596V500V353H707Q722 345 722 333Q722 320 707 313H409V40H707Q722 32 722 20T707 0H70Q56 7 56 20T70 40H369V313H70Q56 320 56 333Z"></path></g><g data-mml-node="mn" transform="translate(3111.4,0)"><path data-c="32" d="M109 429Q82 429 66 447T50 491Q50 562 103 614T235 666Q326 666 387 610T449 465Q449 422 429 383T381 315T301 241Q265 210 201 149L142 93L218 92Q375 92 385 97Q392 99 409 186V189H449V186Q448 183 436 95T421 3V0H50V19V31Q50 38 56 46T86 81Q115 113 136 137Q145 147 170 174T204 211T233 244T261 278T284 308T305 340T320 369T333 401T340 431T343 464Q343 527 309 573T212 619Q179 619 154 602T119 569T109 550Q109 549 114 549Q132 549 151 535T170 489Q170 464 154 447T109 429Z"></path><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z" transform="translate(500,0)"></path></g><g data-mml-node="mo" transform="translate(4111.4,0)"><path data-c="29" d="M60 749L64 750Q69 750 74 750H86L114 726Q208 641 251 514T294 250Q294 182 284 119T261 12T224 -76T186 -143T145 -194T113 -227T90 -246Q87 -249 86 -250H74Q66 -250 63 -250T58 -247T55 -238Q56 -237 66 -225Q221 -64 221 250T66 725Q56 737 55 738Q55 746 60 749Z"></path></g><g data-mml-node="mi" transform="translate(4500.4,0)"><path data-c="1D454" d="M311 43Q296 30 267 15T206 0Q143 0 105 45T66 160Q66 265 143 353T314 442Q361 442 401 394L404 398Q406 401 409 404T418 412T431 419T447 422Q461 422 470 413T480 394Q480 379 423 152T363 -80Q345 -134 286 -169T151 -205Q10 -205 10 -137Q10 -111 28 -91T74 -71Q89 -71 102 -80T116 -111Q116 -121 114 -130T107 -144T99 -154T92 -162L90 -164H91Q101 -167 151 -167Q189 -167 211 -155Q234 -144 254 -122T282 -75Q288 -56 298 -13Q311 35 311 43ZM384 328L380 339Q377 350 375 354T369 368T359 382T346 393T328 402T306 405Q262 405 221 352Q191 313 171 233T151 117Q151 38 213 38Q269 38 323 108L331 118L384 328Z"></path></g><g data-mml-node="TeXAtom" data-mjx-texclass="ORD" transform="translate(4977.4,0)"><g data-mml-node="mo"><path data-c="2F" d="M423 750Q432 750 438 744T444 730Q444 725 271 248T92 -240Q85 -250 75 -250Q68 -250 62 -245T56 -231Q56 -221 230 257T407 740Q411 750 423 750Z"></path></g></g><g data-mml-node="mi" transform="translate(5477.4,0)"><path data-c="1D43F" d="M228 637Q194 637 192 641Q191 643 191 649Q191 673 202 682Q204 683 217 683Q271 680 344 680Q485 680 506 683H518Q524 677 524 674T522 656Q517 641 513 637H475Q406 636 394 628Q387 624 380 600T313 336Q297 271 279 198T252 88L243 52Q243 48 252 48T311 46H328Q360 46 379 47T428 54T478 72T522 106T564 161Q580 191 594 228T611 270Q616 273 628 273H641Q647 264 647 262T627 203T583 83T557 9Q555 4 553 3T537 0T494 -1Q483 -1 418 -1T294 0H116Q32 0 32 10Q32 17 34 24Q39 43 44 45Q48 46 59 46H65Q92 46 125 49Q139 52 144 61Q147 65 216 339T285 628Q285 635 228 637Z"></path></g></g></g></svg></mjx-container>, 女性 <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.566ex;" xmlns="http://www.w3.org/2000/svg" width="13.933ex" height="2.262ex" role="img" focusable="false" viewBox="0 -750 6158.4 1000"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="mo"><path data-c="28" d="M94 250Q94 319 104 381T127 488T164 576T202 643T244 695T277 729T302 750H315H319Q333 750 333 741Q333 738 316 720T275 667T226 581T184 443T167 250T184 58T225 -81T274 -167T316 -220T333 -241Q333 -250 318 -250H315H302L274 -226Q180 -141 137 -14T94 250Z"></path></g><g data-mml-node="mn" transform="translate(389,0)"><path data-c="31" d="M213 578L200 573Q186 568 160 563T102 556H83V602H102Q149 604 189 617T245 641T273 663Q275 666 285 666Q294 666 302 660V361L303 61Q310 54 315 52T339 48T401 46H427V0H416Q395 3 257 3Q121 3 100 0H88V46H114Q136 46 152 46T177 47T193 50T201 52T207 57T213 61V578Z"></path><path data-c="33" d="M127 463Q100 463 85 480T69 524Q69 579 117 622T233 665Q268 665 277 664Q351 652 390 611T430 522Q430 470 396 421T302 350L299 348Q299 347 308 345T337 336T375 315Q457 262 457 175Q457 96 395 37T238 -22Q158 -22 100 21T42 130Q42 158 60 175T105 193Q133 193 151 175T169 130Q169 119 166 110T159 94T148 82T136 74T126 70T118 67L114 66Q165 21 238 21Q293 21 321 74Q338 107 338 175V195Q338 290 274 322Q259 328 213 329L171 330L168 332Q166 335 166 348Q166 366 174 366Q202 366 232 371Q266 376 294 413T322 525V533Q322 590 287 612Q265 626 240 626Q208 626 181 615T143 592T132 580H135Q138 579 143 578T153 573T165 566T175 555T183 540T186 520Q186 498 172 481T127 463Z" transform="translate(500,0)"></path><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z" transform="translate(1000,0)"></path></g><g data-mml-node="mo" transform="translate(2111.2,0)"><path data-c="B1" d="M56 320T56 333T70 353H369V502Q369 651 371 655Q376 666 388 666Q402 666 405 654T409 596V500V353H707Q722 345 722 333Q722 320 707 313H409V40H707Q722 32 722 20T707 0H70Q56 7 56 20T70 40H369V313H70Q56 320 56 333Z"></path></g><g data-mml-node="mn" transform="translate(3111.4,0)"><path data-c="32" d="M109 429Q82 429 66 447T50 491Q50 562 103 614T235 666Q326 666 387 610T449 465Q449 422 429 383T381 315T301 241Q265 210 201 149L142 93L218 92Q375 92 385 97Q392 99 409 186V189H449V186Q448 183 436 95T421 3V0H50V19V31Q50 38 56 46T86 81Q115 113 136 137Q145 147 170 174T204 211T233 244T261 278T284 308T305 340T320 369T333 401T340 431T343 464Q343 527 309 573T212 619Q179 619 154 602T119 569T109 550Q109 549 114 549Q132 549 151 535T170 489Q170 464 154 447T109 429Z"></path><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z" transform="translate(500,0)"></path></g><g data-mml-node="mo" transform="translate(4111.4,0)"><path data-c="29" d="M60 749L64 750Q69 750 74 750H86L114 726Q208 641 251 514T294 250Q294 182 284 119T261 12T224 -76T186 -143T145 -194T113 -227T90 -246Q87 -249 86 -250H74Q66 -250 63 -250T58 -247T55 -238Q56 -237 66 -225Q221 -64 221 250T66 725Q56 737 55 738Q55 746 60 749Z"></path></g><g data-mml-node="mi" transform="translate(4500.4,0)"><path data-c="1D454" d="M311 43Q296 30 267 15T206 0Q143 0 105 45T66 160Q66 265 143 353T314 442Q361 442 401 394L404 398Q406 401 409 404T418 412T431 419T447 422Q461 422 470 413T480 394Q480 379 423 152T363 -80Q345 -134 286 -169T151 -205Q10 -205 10 -137Q10 -111 28 -91T74 -71Q89 -71 102 -80T116 -111Q116 -121 114 -130T107 -144T99 -154T92 -162L90 -164H91Q101 -167 151 -167Q189 -167 211 -155Q234 -144 254 -122T282 -75Q288 -56 298 -13Q311 35 311 43ZM384 328L380 339Q377 350 375 354T369 368T359 382T346 393T328 402T306 405Q262 405 221 352Q191 313 171 233T151 117Q151 38 213 38Q269 38 323 108L331 118L384 328Z"></path></g><g data-mml-node="TeXAtom" data-mjx-texclass="ORD" transform="translate(4977.4,0)"><g data-mml-node="mo"><path data-c="2F" d="M423 750Q432 750 438 744T444 730Q444 725 271 248T92 -240Q85 -250 75 -250Q68 -250 62 -245T56 -231Q56 -221 230 257T407 740Q411 750 423 750Z"></path></g></g><g data-mml-node="mi" transform="translate(5477.4,0)"><path data-c="1D43F" d="M228 637Q194 637 192 641Q191 643 191 649Q191 673 202 682Q204 683 217 683Q271 680 344 680Q485 680 506 683H518Q524 677 524 674T522 656Q517 641 513 637H475Q406 636 394 628Q387 624 380 600T313 336Q297 271 279 198T252 88L243 52Q243 48 252 48T311 46H328Q360 46 379 47T428 54T478 72T522 106T564 161Q580 191 594 228T611 270Q616 273 628 273H641Q647 264 647 262T627 203T583 83T557 9Q555 4 553 3T537 0T494 -1Q483 -1 418 -1T294 0H116Q32 0 32 10Q32 17 34 24Q39 43 44 45Q48 46 59 46H65Q92 46 125 49Q139 52 144 61Q147 65 216 339T285 628Q285 635 228 637Z"></path></g></g></g></svg></mjx-container></li> -<li>异常情况<ol> +<li>异常情况 +<ol> <li>升高: 真性红细胞增多症, 严重脱水, 肺源性心脏病, 先天性心脏病, 高山地区的居民和严重烧伤等</li> <li>降低: 贫血</li> </ol> </li> </ul> </li> -<li>白细胞 (WBC)<ul> +<li>白细胞 (WBC) +<ul> <li>正常情况: 男女都是 <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.566ex;" xmlns="http://www.w3.org/2000/svg" width="15.476ex" height="2.52ex" role="img" focusable="false" viewBox="0 -864 6840.4 1114"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="mo"><path data-c="28" d="M94 250Q94 319 104 381T127 488T164 576T202 643T244 695T277 729T302 750H315H319Q333 750 333 741Q333 738 316 720T275 667T226 581T184 443T167 250T184 58T225 -81T274 -167T316 -220T333 -241Q333 -250 318 -250H315H302L274 -226Q180 -141 137 -14T94 250Z"></path></g><g data-mml-node="mn" transform="translate(389,0)"><path data-c="37" d="M55 458Q56 460 72 567L88 674Q88 676 108 676H128V672Q128 662 143 655T195 646T364 644H485V605L417 512Q408 500 387 472T360 435T339 403T319 367T305 330T292 284T284 230T278 162T275 80Q275 66 275 52T274 28V19Q270 2 255 -10T221 -22Q210 -22 200 -19T179 0T168 40Q168 198 265 368Q285 400 349 489L395 552H302Q128 552 119 546Q113 543 108 522T98 479L95 458V455H55V458Z"></path></g><g data-mml-node="mo" transform="translate(1111.2,0)"><path data-c="B1" d="M56 320T56 333T70 353H369V502Q369 651 371 655Q376 666 388 666Q402 666 405 654T409 596V500V353H707Q722 345 722 333Q722 320 707 313H409V40H707Q722 32 722 20T707 0H70Q56 7 56 20T70 40H369V313H70Q56 320 56 333Z"></path></g><g data-mml-node="mn" transform="translate(2111.4,0)"><path data-c="33" d="M127 463Q100 463 85 480T69 524Q69 579 117 622T233 665Q268 665 277 664Q351 652 390 611T430 522Q430 470 396 421T302 350L299 348Q299 347 308 345T337 336T375 315Q457 262 457 175Q457 96 395 37T238 -22Q158 -22 100 21T42 130Q42 158 60 175T105 193Q133 193 151 175T169 130Q169 119 166 110T159 94T148 82T136 74T126 70T118 67L114 66Q165 21 238 21Q293 21 321 74Q338 107 338 175V195Q338 290 274 322Q259 328 213 329L171 330L168 332Q166 335 166 348Q166 366 174 366Q202 366 232 371Q266 376 294 413T322 525V533Q322 590 287 612Q265 626 240 626Q208 626 181 615T143 592T132 580H135Q138 579 143 578T153 573T165 566T175 555T183 540T186 520Q186 498 172 481T127 463Z"></path></g><g data-mml-node="mo" transform="translate(2611.4,0)"><path data-c="29" d="M60 749L64 750Q69 750 74 750H86L114 726Q208 641 251 514T294 250Q294 182 284 119T261 12T224 -76T186 -143T145 -194T113 -227T90 -246Q87 -249 86 -250H74Q66 -250 63 -250T58 -247T55 -238Q56 -237 66 -225Q221 -64 221 250T66 725Q56 737 55 738Q55 746 60 749Z"></path></g><g data-mml-node="mo" transform="translate(3222.7,0)"><path data-c="D7" d="M630 29Q630 9 609 9Q604 9 587 25T493 118L389 222L284 117Q178 13 175 11Q171 9 168 9Q160 9 154 15T147 29Q147 36 161 51T255 146L359 250L255 354Q174 435 161 449T147 471Q147 480 153 485T168 490Q173 490 175 489Q178 487 284 383L389 278L493 382Q570 459 587 475T609 491Q630 491 630 471Q630 464 620 453T522 355L418 250L522 145Q606 61 618 48T630 29Z"></path></g><g data-mml-node="msup" transform="translate(4222.9,0)"><g data-mml-node="mn"><path data-c="31" d="M213 578L200 573Q186 568 160 563T102 556H83V602H102Q149 604 189 617T245 641T273 663Q275 666 285 666Q294 666 302 660V361L303 61Q310 54 315 52T339 48T401 46H427V0H416Q395 3 257 3Q121 3 100 0H88V46H114Q136 46 152 46T177 47T193 50T201 52T207 57T213 61V578Z"></path><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z" transform="translate(500,0)"></path></g><g data-mml-node="mn" transform="translate(1033,393.1) scale(0.707)"><path data-c="39" d="M352 287Q304 211 232 211Q154 211 104 270T44 396Q42 412 42 436V444Q42 537 111 606Q171 666 243 666Q245 666 249 666T257 665H261Q273 665 286 663T323 651T370 619T413 560Q456 472 456 334Q456 194 396 97Q361 41 312 10T208 -22Q147 -22 108 7T68 93T121 149Q143 149 158 135T173 96Q173 78 164 65T148 49T135 44L131 43Q131 41 138 37T164 27T206 22H212Q272 22 313 86Q352 142 352 280V287ZM244 248Q292 248 321 297T351 430Q351 508 343 542Q341 552 337 562T323 588T293 615T246 625Q208 625 181 598Q160 576 154 546T147 441Q147 358 152 329T172 282Q197 248 244 248Z"></path></g></g><g data-mml-node="TeXAtom" data-mjx-texclass="ORD" transform="translate(5659.4,0)"><g data-mml-node="mo"><path data-c="2F" d="M423 750Q432 750 438 744T444 730Q444 725 271 248T92 -240Q85 -250 75 -250Q68 -250 62 -245T56 -231Q56 -221 230 257T407 740Q411 750 423 750Z"></path></g></g><g data-mml-node="mi" transform="translate(6159.4,0)"><path data-c="1D43F" d="M228 637Q194 637 192 641Q191 643 191 649Q191 673 202 682Q204 683 217 683Q271 680 344 680Q485 680 506 683H518Q524 677 524 674T522 656Q517 641 513 637H475Q406 636 394 628Q387 624 380 600T313 336Q297 271 279 198T252 88L243 52Q243 48 252 48T311 46H328Q360 46 379 47T428 54T478 72T522 106T564 161Q580 191 594 228T611 270Q616 273 628 273H641Q647 264 647 262T627 203T583 83T557 9Q555 4 553 3T537 0T494 -1Q483 -1 418 -1T294 0H116Q32 0 32 10Q32 17 34 24Q39 43 44 45Q48 46 59 46H65Q92 46 125 49Q139 52 144 61Q147 65 216 339T285 628Q285 635 228 637Z"></path></g></g></g></svg></mjx-container></li> -<li>异常情况<ol> -<li>升高: 各种细胞感染, 炎症, 严重烧伤<ul> -<li><h3 id="当白细胞明显升高,-甚至于-350-pm-150-times-10-9-L-,-并伴有发热,出血,贫血等症状的时候,应当警惕白血病"><a href="#当白细胞明显升高,-甚至于-350-pm-150-times-10-9-L-,-并伴有发热,出血,贫血等症状的时候,应当警惕白血病" class="headerlink" title="当白细胞明显升高, 甚至于 $(350 \pm 150) \times 10^9 / L$ , 并伴有发热,出血,贫血等症状的时候,应当警惕白血病"></a>当白细胞明显升高, 甚至于 <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.566ex;" xmlns="http://www.w3.org/2000/svg" width="20.001ex" height="2.52ex" role="img" focusable="false" viewBox="0 -864 8840.4 1114"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="mo"><path data-c="28" d="M94 250Q94 319 104 381T127 488T164 576T202 643T244 695T277 729T302 750H315H319Q333 750 333 741Q333 738 316 720T275 667T226 581T184 443T167 250T184 58T225 -81T274 -167T316 -220T333 -241Q333 -250 318 -250H315H302L274 -226Q180 -141 137 -14T94 250Z"></path></g><g data-mml-node="mn" transform="translate(389,0)"><path data-c="33" d="M127 463Q100 463 85 480T69 524Q69 579 117 622T233 665Q268 665 277 664Q351 652 390 611T430 522Q430 470 396 421T302 350L299 348Q299 347 308 345T337 336T375 315Q457 262 457 175Q457 96 395 37T238 -22Q158 -22 100 21T42 130Q42 158 60 175T105 193Q133 193 151 175T169 130Q169 119 166 110T159 94T148 82T136 74T126 70T118 67L114 66Q165 21 238 21Q293 21 321 74Q338 107 338 175V195Q338 290 274 322Q259 328 213 329L171 330L168 332Q166 335 166 348Q166 366 174 366Q202 366 232 371Q266 376 294 413T322 525V533Q322 590 287 612Q265 626 240 626Q208 626 181 615T143 592T132 580H135Q138 579 143 578T153 573T165 566T175 555T183 540T186 520Q186 498 172 481T127 463Z"></path><path data-c="35" d="M164 157Q164 133 148 117T109 101H102Q148 22 224 22Q294 22 326 82Q345 115 345 210Q345 313 318 349Q292 382 260 382H254Q176 382 136 314Q132 307 129 306T114 304Q97 304 95 310Q93 314 93 485V614Q93 664 98 664Q100 666 102 666Q103 666 123 658T178 642T253 634Q324 634 389 662Q397 666 402 666Q410 666 410 648V635Q328 538 205 538Q174 538 149 544L139 546V374Q158 388 169 396T205 412T256 420Q337 420 393 355T449 201Q449 109 385 44T229 -22Q148 -22 99 32T50 154Q50 178 61 192T84 210T107 214Q132 214 148 197T164 157Z" transform="translate(500,0)"></path><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z" transform="translate(1000,0)"></path></g><g data-mml-node="mo" transform="translate(2111.2,0)"><path data-c="B1" d="M56 320T56 333T70 353H369V502Q369 651 371 655Q376 666 388 666Q402 666 405 654T409 596V500V353H707Q722 345 722 333Q722 320 707 313H409V40H707Q722 32 722 20T707 0H70Q56 7 56 20T70 40H369V313H70Q56 320 56 333Z"></path></g><g data-mml-node="mn" transform="translate(3111.4,0)"><path data-c="31" d="M213 578L200 573Q186 568 160 563T102 556H83V602H102Q149 604 189 617T245 641T273 663Q275 666 285 666Q294 666 302 660V361L303 61Q310 54 315 52T339 48T401 46H427V0H416Q395 3 257 3Q121 3 100 0H88V46H114Q136 46 152 46T177 47T193 50T201 52T207 57T213 61V578Z"></path><path data-c="35" d="M164 157Q164 133 148 117T109 101H102Q148 22 224 22Q294 22 326 82Q345 115 345 210Q345 313 318 349Q292 382 260 382H254Q176 382 136 314Q132 307 129 306T114 304Q97 304 95 310Q93 314 93 485V614Q93 664 98 664Q100 666 102 666Q103 666 123 658T178 642T253 634Q324 634 389 662Q397 666 402 666Q410 666 410 648V635Q328 538 205 538Q174 538 149 544L139 546V374Q158 388 169 396T205 412T256 420Q337 420 393 355T449 201Q449 109 385 44T229 -22Q148 -22 99 32T50 154Q50 178 61 192T84 210T107 214Q132 214 148 197T164 157Z" transform="translate(500,0)"></path><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z" transform="translate(1000,0)"></path></g><g data-mml-node="mo" transform="translate(4611.4,0)"><path data-c="29" d="M60 749L64 750Q69 750 74 750H86L114 726Q208 641 251 514T294 250Q294 182 284 119T261 12T224 -76T186 -143T145 -194T113 -227T90 -246Q87 -249 86 -250H74Q66 -250 63 -250T58 -247T55 -238Q56 -237 66 -225Q221 -64 221 250T66 725Q56 737 55 738Q55 746 60 749Z"></path></g><g data-mml-node="mo" transform="translate(5222.7,0)"><path data-c="D7" d="M630 29Q630 9 609 9Q604 9 587 25T493 118L389 222L284 117Q178 13 175 11Q171 9 168 9Q160 9 154 15T147 29Q147 36 161 51T255 146L359 250L255 354Q174 435 161 449T147 471Q147 480 153 485T168 490Q173 490 175 489Q178 487 284 383L389 278L493 382Q570 459 587 475T609 491Q630 491 630 471Q630 464 620 453T522 355L418 250L522 145Q606 61 618 48T630 29Z"></path></g><g data-mml-node="msup" transform="translate(6222.9,0)"><g data-mml-node="mn"><path data-c="31" d="M213 578L200 573Q186 568 160 563T102 556H83V602H102Q149 604 189 617T245 641T273 663Q275 666 285 666Q294 666 302 660V361L303 61Q310 54 315 52T339 48T401 46H427V0H416Q395 3 257 3Q121 3 100 0H88V46H114Q136 46 152 46T177 47T193 50T201 52T207 57T213 61V578Z"></path><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z" transform="translate(500,0)"></path></g><g data-mml-node="mn" transform="translate(1033,393.1) scale(0.707)"><path data-c="39" d="M352 287Q304 211 232 211Q154 211 104 270T44 396Q42 412 42 436V444Q42 537 111 606Q171 666 243 666Q245 666 249 666T257 665H261Q273 665 286 663T323 651T370 619T413 560Q456 472 456 334Q456 194 396 97Q361 41 312 10T208 -22Q147 -22 108 7T68 93T121 149Q143 149 158 135T173 96Q173 78 164 65T148 49T135 44L131 43Q131 41 138 37T164 27T206 22H212Q272 22 313 86Q352 142 352 280V287ZM244 248Q292 248 321 297T351 430Q351 508 343 542Q341 552 337 562T323 588T293 615T246 625Q208 625 181 598Q160 576 154 546T147 441Q147 358 152 329T172 282Q197 248 244 248Z"></path></g></g><g data-mml-node="TeXAtom" data-mjx-texclass="ORD" transform="translate(7659.4,0)"><g data-mml-node="mo"><path data-c="2F" d="M423 750Q432 750 438 744T444 730Q444 725 271 248T92 -240Q85 -250 75 -250Q68 -250 62 -245T56 -231Q56 -221 230 257T407 740Q411 750 423 750Z"></path></g></g><g data-mml-node="mi" transform="translate(8159.4,0)"><path data-c="1D43F" d="M228 637Q194 637 192 641Q191 643 191 649Q191 673 202 682Q204 683 217 683Q271 680 344 680Q485 680 506 683H518Q524 677 524 674T522 656Q517 641 513 637H475Q406 636 394 628Q387 624 380 600T313 336Q297 271 279 198T252 88L243 52Q243 48 252 48T311 46H328Q360 46 379 47T428 54T478 72T522 106T564 161Q580 191 594 228T611 270Q616 273 628 273H641Q647 264 647 262T627 203T583 83T557 9Q555 4 553 3T537 0T494 -1Q483 -1 418 -1T294 0H116Q32 0 32 10Q32 17 34 24Q39 43 44 45Q48 46 59 46H65Q92 46 125 49Q139 52 144 61Q147 65 216 339T285 628Q285 635 228 637Z"></path></g></g></g></svg></mjx-container> , 并伴有发热,出血,贫血等症状的时候,应当警惕白血病</h3></li> +<li>异常情况 +<ol> +<li>升高: 各种细胞感染, 炎症, 严重烧伤 +<ul> +<li> +<h3 id="当白细胞明显升高,-甚至于-350-pm-150-times-10-9-L-,-并伴有发热,出血,贫血等症状的时候,应当警惕白血病"><a class="header-anchor" href="#当白细胞明显升高,-甚至于-350-pm-150-times-10-9-L-,-并伴有发热,出血,贫血等症状的时候,应当警惕白血病">¶</a>当白细胞明显升高, 甚至于 <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.566ex;" xmlns="http://www.w3.org/2000/svg" width="20.001ex" height="2.52ex" role="img" focusable="false" viewBox="0 -864 8840.4 1114"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="mo"><path data-c="28" d="M94 250Q94 319 104 381T127 488T164 576T202 643T244 695T277 729T302 750H315H319Q333 750 333 741Q333 738 316 720T275 667T226 581T184 443T167 250T184 58T225 -81T274 -167T316 -220T333 -241Q333 -250 318 -250H315H302L274 -226Q180 -141 137 -14T94 250Z"></path></g><g data-mml-node="mn" transform="translate(389,0)"><path data-c="33" d="M127 463Q100 463 85 480T69 524Q69 579 117 622T233 665Q268 665 277 664Q351 652 390 611T430 522Q430 470 396 421T302 350L299 348Q299 347 308 345T337 336T375 315Q457 262 457 175Q457 96 395 37T238 -22Q158 -22 100 21T42 130Q42 158 60 175T105 193Q133 193 151 175T169 130Q169 119 166 110T159 94T148 82T136 74T126 70T118 67L114 66Q165 21 238 21Q293 21 321 74Q338 107 338 175V195Q338 290 274 322Q259 328 213 329L171 330L168 332Q166 335 166 348Q166 366 174 366Q202 366 232 371Q266 376 294 413T322 525V533Q322 590 287 612Q265 626 240 626Q208 626 181 615T143 592T132 580H135Q138 579 143 578T153 573T165 566T175 555T183 540T186 520Q186 498 172 481T127 463Z"></path><path data-c="35" d="M164 157Q164 133 148 117T109 101H102Q148 22 224 22Q294 22 326 82Q345 115 345 210Q345 313 318 349Q292 382 260 382H254Q176 382 136 314Q132 307 129 306T114 304Q97 304 95 310Q93 314 93 485V614Q93 664 98 664Q100 666 102 666Q103 666 123 658T178 642T253 634Q324 634 389 662Q397 666 402 666Q410 666 410 648V635Q328 538 205 538Q174 538 149 544L139 546V374Q158 388 169 396T205 412T256 420Q337 420 393 355T449 201Q449 109 385 44T229 -22Q148 -22 99 32T50 154Q50 178 61 192T84 210T107 214Q132 214 148 197T164 157Z" transform="translate(500,0)"></path><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z" transform="translate(1000,0)"></path></g><g data-mml-node="mo" transform="translate(2111.2,0)"><path data-c="B1" d="M56 320T56 333T70 353H369V502Q369 651 371 655Q376 666 388 666Q402 666 405 654T409 596V500V353H707Q722 345 722 333Q722 320 707 313H409V40H707Q722 32 722 20T707 0H70Q56 7 56 20T70 40H369V313H70Q56 320 56 333Z"></path></g><g data-mml-node="mn" transform="translate(3111.4,0)"><path data-c="31" d="M213 578L200 573Q186 568 160 563T102 556H83V602H102Q149 604 189 617T245 641T273 663Q275 666 285 666Q294 666 302 660V361L303 61Q310 54 315 52T339 48T401 46H427V0H416Q395 3 257 3Q121 3 100 0H88V46H114Q136 46 152 46T177 47T193 50T201 52T207 57T213 61V578Z"></path><path data-c="35" d="M164 157Q164 133 148 117T109 101H102Q148 22 224 22Q294 22 326 82Q345 115 345 210Q345 313 318 349Q292 382 260 382H254Q176 382 136 314Q132 307 129 306T114 304Q97 304 95 310Q93 314 93 485V614Q93 664 98 664Q100 666 102 666Q103 666 123 658T178 642T253 634Q324 634 389 662Q397 666 402 666Q410 666 410 648V635Q328 538 205 538Q174 538 149 544L139 546V374Q158 388 169 396T205 412T256 420Q337 420 393 355T449 201Q449 109 385 44T229 -22Q148 -22 99 32T50 154Q50 178 61 192T84 210T107 214Q132 214 148 197T164 157Z" transform="translate(500,0)"></path><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z" transform="translate(1000,0)"></path></g><g data-mml-node="mo" transform="translate(4611.4,0)"><path data-c="29" d="M60 749L64 750Q69 750 74 750H86L114 726Q208 641 251 514T294 250Q294 182 284 119T261 12T224 -76T186 -143T145 -194T113 -227T90 -246Q87 -249 86 -250H74Q66 -250 63 -250T58 -247T55 -238Q56 -237 66 -225Q221 -64 221 250T66 725Q56 737 55 738Q55 746 60 749Z"></path></g><g data-mml-node="mo" transform="translate(5222.7,0)"><path data-c="D7" d="M630 29Q630 9 609 9Q604 9 587 25T493 118L389 222L284 117Q178 13 175 11Q171 9 168 9Q160 9 154 15T147 29Q147 36 161 51T255 146L359 250L255 354Q174 435 161 449T147 471Q147 480 153 485T168 490Q173 490 175 489Q178 487 284 383L389 278L493 382Q570 459 587 475T609 491Q630 491 630 471Q630 464 620 453T522 355L418 250L522 145Q606 61 618 48T630 29Z"></path></g><g data-mml-node="msup" transform="translate(6222.9,0)"><g data-mml-node="mn"><path data-c="31" d="M213 578L200 573Q186 568 160 563T102 556H83V602H102Q149 604 189 617T245 641T273 663Q275 666 285 666Q294 666 302 660V361L303 61Q310 54 315 52T339 48T401 46H427V0H416Q395 3 257 3Q121 3 100 0H88V46H114Q136 46 152 46T177 47T193 50T201 52T207 57T213 61V578Z"></path><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z" transform="translate(500,0)"></path></g><g data-mml-node="mn" transform="translate(1033,393.1) scale(0.707)"><path data-c="39" d="M352 287Q304 211 232 211Q154 211 104 270T44 396Q42 412 42 436V444Q42 537 111 606Q171 666 243 666Q245 666 249 666T257 665H261Q273 665 286 663T323 651T370 619T413 560Q456 472 456 334Q456 194 396 97Q361 41 312 10T208 -22Q147 -22 108 7T68 93T121 149Q143 149 158 135T173 96Q173 78 164 65T148 49T135 44L131 43Q131 41 138 37T164 27T206 22H212Q272 22 313 86Q352 142 352 280V287ZM244 248Q292 248 321 297T351 430Q351 508 343 542Q341 552 337 562T323 588T293 615T246 625Q208 625 181 598Q160 576 154 546T147 441Q147 358 152 329T172 282Q197 248 244 248Z"></path></g></g><g data-mml-node="TeXAtom" data-mjx-texclass="ORD" transform="translate(7659.4,0)"><g data-mml-node="mo"><path data-c="2F" d="M423 750Q432 750 438 744T444 730Q444 725 271 248T92 -240Q85 -250 75 -250Q68 -250 62 -245T56 -231Q56 -221 230 257T407 740Q411 750 423 750Z"></path></g></g><g data-mml-node="mi" transform="translate(8159.4,0)"><path data-c="1D43F" d="M228 637Q194 637 192 641Q191 643 191 649Q191 673 202 682Q204 683 217 683Q271 680 344 680Q485 680 506 683H518Q524 677 524 674T522 656Q517 641 513 637H475Q406 636 394 628Q387 624 380 600T313 336Q297 271 279 198T252 88L243 52Q243 48 252 48T311 46H328Q360 46 379 47T428 54T478 72T522 106T564 161Q580 191 594 228T611 270Q616 273 628 273H641Q647 264 647 262T627 203T583 83T557 9Q555 4 553 3T537 0T494 -1Q483 -1 418 -1T294 0H116Q32 0 32 10Q32 17 34 24Q39 43 44 45Q48 46 59 46H65Q92 46 125 49Q139 52 144 61Q147 65 216 339T285 628Q285 635 228 637Z"></path></g></g></g></svg></mjx-container> , 并伴有发热,出血,贫血等症状的时候,应当警惕白血病</h3> +</li> </ul> </li> <li>降低: 白细胞减少症, 脾功能亢进, 造血功能障碍等</li> @@ -5293,27 +5895,33 @@ await prisma.$transaction(async tx => { </li> </ul> </li> -<li>中性粒细胞比率 (NEUTP)<ul> +<li>中性粒细胞比率 (NEUTP) +<ul> <li>正常情况: 男女都是 <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.566ex;" xmlns="http://www.w3.org/2000/svg" width="9.051ex" height="2.262ex" role="img" focusable="false" viewBox="0 -750 4000.4 1000"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="mo"><path data-c="28" d="M94 250Q94 319 104 381T127 488T164 576T202 643T244 695T277 729T302 750H315H319Q333 750 333 741Q333 738 316 720T275 667T226 581T184 443T167 250T184 58T225 -81T274 -167T316 -220T333 -241Q333 -250 318 -250H315H302L274 -226Q180 -141 137 -14T94 250Z"></path></g><g data-mml-node="mn" transform="translate(389,0)"><path data-c="36" d="M42 313Q42 476 123 571T303 666Q372 666 402 630T432 550Q432 525 418 510T379 495Q356 495 341 509T326 548Q326 592 373 601Q351 623 311 626Q240 626 194 566Q147 500 147 364L148 360Q153 366 156 373Q197 433 263 433H267Q313 433 348 414Q372 400 396 374T435 317Q456 268 456 210V192Q456 169 451 149Q440 90 387 34T253 -22Q225 -22 199 -14T143 16T92 75T56 172T42 313ZM257 397Q227 397 205 380T171 335T154 278T148 216Q148 133 160 97T198 39Q222 21 251 21Q302 21 329 59Q342 77 347 104T352 209Q352 289 347 316T329 361Q302 397 257 397Z"></path><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z" transform="translate(500,0)"></path></g><g data-mml-node="mo" transform="translate(1611.2,0)"><path data-c="B1" d="M56 320T56 333T70 353H369V502Q369 651 371 655Q376 666 388 666Q402 666 405 654T409 596V500V353H707Q722 345 722 333Q722 320 707 313H409V40H707Q722 32 722 20T707 0H70Q56 7 56 20T70 40H369V313H70Q56 320 56 333Z"></path></g><g data-mml-node="mn" transform="translate(2611.4,0)"><path data-c="31" d="M213 578L200 573Q186 568 160 563T102 556H83V602H102Q149 604 189 617T245 641T273 663Q275 666 285 666Q294 666 302 660V361L303 61Q310 54 315 52T339 48T401 46H427V0H416Q395 3 257 3Q121 3 100 0H88V46H114Q136 46 152 46T177 47T193 50T201 52T207 57T213 61V578Z"></path><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z" transform="translate(500,0)"></path></g><g data-mml-node="mo" transform="translate(3611.4,0)"><path data-c="29" d="M60 749L64 750Q69 750 74 750H86L114 726Q208 641 251 514T294 250Q294 182 284 119T261 12T224 -76T186 -143T145 -194T113 -227T90 -246Q87 -249 86 -250H74Q66 -250 63 -250T58 -247T55 -238Q56 -237 66 -225Q221 -64 221 250T66 725Q56 737 55 738Q55 746 60 749Z"></path></g></g></g></svg></mjx-container></li> -<li>异常情况<ul> +<li>异常情况 +<ul> <li>升高:炎症, 各种感染 (细菌病毒都有)</li> <li>降低: 各种感染 (病毒感染多见), 中性粒细胞减少症</li> </ul> </li> </ul> </li> -<li>淋巴细胞数 (LYM)<ul> +<li>淋巴细胞数 (LYM) +<ul> <li>正常情况: 男女都是 <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.566ex;" xmlns="http://www.w3.org/2000/svg" width="18.996ex" height="2.52ex" role="img" focusable="false" viewBox="0 -864 8396.4 1114"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="mo"><path data-c="28" d="M94 250Q94 319 104 381T127 488T164 576T202 643T244 695T277 729T302 750H315H319Q333 750 333 741Q333 738 316 720T275 667T226 581T184 443T167 250T184 58T225 -81T274 -167T316 -220T333 -241Q333 -250 318 -250H315H302L274 -226Q180 -141 137 -14T94 250Z"></path></g><g data-mml-node="mn" transform="translate(389,0)"><path data-c="32" d="M109 429Q82 429 66 447T50 491Q50 562 103 614T235 666Q326 666 387 610T449 465Q449 422 429 383T381 315T301 241Q265 210 201 149L142 93L218 92Q375 92 385 97Q392 99 409 186V189H449V186Q448 183 436 95T421 3V0H50V19V31Q50 38 56 46T86 81Q115 113 136 137Q145 147 170 174T204 211T233 244T261 278T284 308T305 340T320 369T333 401T340 431T343 464Q343 527 309 573T212 619Q179 619 154 602T119 569T109 550Q109 549 114 549Q132 549 151 535T170 489Q170 464 154 447T109 429Z"></path><path data-c="2E" d="M78 60Q78 84 95 102T138 120Q162 120 180 104T199 61Q199 36 182 18T139 0T96 17T78 60Z" transform="translate(500,0)"></path><path data-c="34" d="M462 0Q444 3 333 3Q217 3 199 0H190V46H221Q241 46 248 46T265 48T279 53T286 61Q287 63 287 115V165H28V211L179 442Q332 674 334 675Q336 677 355 677H373L379 671V211H471V165H379V114Q379 73 379 66T385 54Q393 47 442 46H471V0H462ZM293 211V545L74 212L183 211H293Z" transform="translate(778,0)"></path></g><g data-mml-node="mo" transform="translate(1889.2,0)"><path data-c="B1" d="M56 320T56 333T70 353H369V502Q369 651 371 655Q376 666 388 666Q402 666 405 654T409 596V500V353H707Q722 345 722 333Q722 320 707 313H409V40H707Q722 32 722 20T707 0H70Q56 7 56 20T70 40H369V313H70Q56 320 56 333Z"></path></g><g data-mml-node="mn" transform="translate(2889.4,0)"><path data-c="31" d="M213 578L200 573Q186 568 160 563T102 556H83V602H102Q149 604 189 617T245 641T273 663Q275 666 285 666Q294 666 302 660V361L303 61Q310 54 315 52T339 48T401 46H427V0H416Q395 3 257 3Q121 3 100 0H88V46H114Q136 46 152 46T177 47T193 50T201 52T207 57T213 61V578Z"></path><path data-c="2E" d="M78 60Q78 84 95 102T138 120Q162 120 180 104T199 61Q199 36 182 18T139 0T96 17T78 60Z" transform="translate(500,0)"></path><path data-c="36" d="M42 313Q42 476 123 571T303 666Q372 666 402 630T432 550Q432 525 418 510T379 495Q356 495 341 509T326 548Q326 592 373 601Q351 623 311 626Q240 626 194 566Q147 500 147 364L148 360Q153 366 156 373Q197 433 263 433H267Q313 433 348 414Q372 400 396 374T435 317Q456 268 456 210V192Q456 169 451 149Q440 90 387 34T253 -22Q225 -22 199 -14T143 16T92 75T56 172T42 313ZM257 397Q227 397 205 380T171 335T154 278T148 216Q148 133 160 97T198 39Q222 21 251 21Q302 21 329 59Q342 77 347 104T352 209Q352 289 347 316T329 361Q302 397 257 397Z" transform="translate(778,0)"></path></g><g data-mml-node="mo" transform="translate(4167.4,0)"><path data-c="29" d="M60 749L64 750Q69 750 74 750H86L114 726Q208 641 251 514T294 250Q294 182 284 119T261 12T224 -76T186 -143T145 -194T113 -227T90 -246Q87 -249 86 -250H74Q66 -250 63 -250T58 -247T55 -238Q56 -237 66 -225Q221 -64 221 250T66 725Q56 737 55 738Q55 746 60 749Z"></path></g><g data-mml-node="mo" transform="translate(4778.7,0)"><path data-c="D7" d="M630 29Q630 9 609 9Q604 9 587 25T493 118L389 222L284 117Q178 13 175 11Q171 9 168 9Q160 9 154 15T147 29Q147 36 161 51T255 146L359 250L255 354Q174 435 161 449T147 471Q147 480 153 485T168 490Q173 490 175 489Q178 487 284 383L389 278L493 382Q570 459 587 475T609 491Q630 491 630 471Q630 464 620 453T522 355L418 250L522 145Q606 61 618 48T630 29Z"></path></g><g data-mml-node="msup" transform="translate(5778.9,0)"><g data-mml-node="mn"><path data-c="31" d="M213 578L200 573Q186 568 160 563T102 556H83V602H102Q149 604 189 617T245 641T273 663Q275 666 285 666Q294 666 302 660V361L303 61Q310 54 315 52T339 48T401 46H427V0H416Q395 3 257 3Q121 3 100 0H88V46H114Q136 46 152 46T177 47T193 50T201 52T207 57T213 61V578Z"></path><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z" transform="translate(500,0)"></path></g><g data-mml-node="mn" transform="translate(1033,393.1) scale(0.707)"><path data-c="39" d="M352 287Q304 211 232 211Q154 211 104 270T44 396Q42 412 42 436V444Q42 537 111 606Q171 666 243 666Q245 666 249 666T257 665H261Q273 665 286 663T323 651T370 619T413 560Q456 472 456 334Q456 194 396 97Q361 41 312 10T208 -22Q147 -22 108 7T68 93T121 149Q143 149 158 135T173 96Q173 78 164 65T148 49T135 44L131 43Q131 41 138 37T164 27T206 22H212Q272 22 313 86Q352 142 352 280V287ZM244 248Q292 248 321 297T351 430Q351 508 343 542Q341 552 337 562T323 588T293 615T246 625Q208 625 181 598Q160 576 154 546T147 441Q147 358 152 329T172 282Q197 248 244 248Z"></path></g></g><g data-mml-node="TeXAtom" data-mjx-texclass="ORD" transform="translate(7215.4,0)"><g data-mml-node="mo"><path data-c="2F" d="M423 750Q432 750 438 744T444 730Q444 725 271 248T92 -240Q85 -250 75 -250Q68 -250 62 -245T56 -231Q56 -221 230 257T407 740Q411 750 423 750Z"></path></g></g><g data-mml-node="mi" transform="translate(7715.4,0)"><path data-c="1D43F" d="M228 637Q194 637 192 641Q191 643 191 649Q191 673 202 682Q204 683 217 683Q271 680 344 680Q485 680 506 683H518Q524 677 524 674T522 656Q517 641 513 637H475Q406 636 394 628Q387 624 380 600T313 336Q297 271 279 198T252 88L243 52Q243 48 252 48T311 46H328Q360 46 379 47T428 54T478 72T522 106T564 161Q580 191 594 228T611 270Q616 273 628 273H641Q647 264 647 262T627 203T583 83T557 9Q555 4 553 3T537 0T494 -1Q483 -1 418 -1T294 0H116Q32 0 32 10Q32 17 34 24Q39 43 44 45Q48 46 59 46H65Q92 46 125 49Q139 52 144 61Q147 65 216 339T285 628Q285 635 228 637Z"></path></g></g></g></svg></mjx-container></li> -<li>异常情况:<ul> +<li>异常情况: +<ul> <li>升高: 百日咳, 传染性单核细胞增多症, 急性传染性淋巴细胞增多症, 淋巴细胞性白血病等</li> <li>降低: 免疫缺陷等</li> </ul> </li> </ul> </li> -<li>血小板 (PLT)<ul> +<li>血小板 (PLT) +<ul> <li>正常情况: 男女都是 <mjx-container class="MathJax" jax="SVG"><svg style="vertical-align: -0.566ex;" xmlns="http://www.w3.org/2000/svg" width="20.001ex" height="2.52ex" role="img" focusable="false" viewBox="0 -864 8840.4 1114"><g stroke="currentColor" fill="currentColor" stroke-width="0" transform="scale(1,-1)"><g data-mml-node="math"><g data-mml-node="mo"><path data-c="28" d="M94 250Q94 319 104 381T127 488T164 576T202 643T244 695T277 729T302 750H315H319Q333 750 333 741Q333 738 316 720T275 667T226 581T184 443T167 250T184 58T225 -81T274 -167T316 -220T333 -241Q333 -250 318 -250H315H302L274 -226Q180 -141 137 -14T94 250Z"></path></g><g data-mml-node="mn" transform="translate(389,0)"><path data-c="32" d="M109 429Q82 429 66 447T50 491Q50 562 103 614T235 666Q326 666 387 610T449 465Q449 422 429 383T381 315T301 241Q265 210 201 149L142 93L218 92Q375 92 385 97Q392 99 409 186V189H449V186Q448 183 436 95T421 3V0H50V19V31Q50 38 56 46T86 81Q115 113 136 137Q145 147 170 174T204 211T233 244T261 278T284 308T305 340T320 369T333 401T340 431T343 464Q343 527 309 573T212 619Q179 619 154 602T119 569T109 550Q109 549 114 549Q132 549 151 535T170 489Q170 464 154 447T109 429Z"></path><path data-c="31" d="M213 578L200 573Q186 568 160 563T102 556H83V602H102Q149 604 189 617T245 641T273 663Q275 666 285 666Q294 666 302 660V361L303 61Q310 54 315 52T339 48T401 46H427V0H416Q395 3 257 3Q121 3 100 0H88V46H114Q136 46 152 46T177 47T193 50T201 52T207 57T213 61V578Z" transform="translate(500,0)"></path><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z" transform="translate(1000,0)"></path></g><g data-mml-node="mo" transform="translate(2111.2,0)"><path data-c="B1" d="M56 320T56 333T70 353H369V502Q369 651 371 655Q376 666 388 666Q402 666 405 654T409 596V500V353H707Q722 345 722 333Q722 320 707 313H409V40H707Q722 32 722 20T707 0H70Q56 7 56 20T70 40H369V313H70Q56 320 56 333Z"></path></g><g data-mml-node="mn" transform="translate(3111.4,0)"><path data-c="31" d="M213 578L200 573Q186 568 160 563T102 556H83V602H102Q149 604 189 617T245 641T273 663Q275 666 285 666Q294 666 302 660V361L303 61Q310 54 315 52T339 48T401 46H427V0H416Q395 3 257 3Q121 3 100 0H88V46H114Q136 46 152 46T177 47T193 50T201 52T207 57T213 61V578Z"></path><path data-c="31" d="M213 578L200 573Q186 568 160 563T102 556H83V602H102Q149 604 189 617T245 641T273 663Q275 666 285 666Q294 666 302 660V361L303 61Q310 54 315 52T339 48T401 46H427V0H416Q395 3 257 3Q121 3 100 0H88V46H114Q136 46 152 46T177 47T193 50T201 52T207 57T213 61V578Z" transform="translate(500,0)"></path><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z" transform="translate(1000,0)"></path></g><g data-mml-node="mo" transform="translate(4611.4,0)"><path data-c="29" d="M60 749L64 750Q69 750 74 750H86L114 726Q208 641 251 514T294 250Q294 182 284 119T261 12T224 -76T186 -143T145 -194T113 -227T90 -246Q87 -249 86 -250H74Q66 -250 63 -250T58 -247T55 -238Q56 -237 66 -225Q221 -64 221 250T66 725Q56 737 55 738Q55 746 60 749Z"></path></g><g data-mml-node="mo" transform="translate(5222.7,0)"><path data-c="D7" d="M630 29Q630 9 609 9Q604 9 587 25T493 118L389 222L284 117Q178 13 175 11Q171 9 168 9Q160 9 154 15T147 29Q147 36 161 51T255 146L359 250L255 354Q174 435 161 449T147 471Q147 480 153 485T168 490Q173 490 175 489Q178 487 284 383L389 278L493 382Q570 459 587 475T609 491Q630 491 630 471Q630 464 620 453T522 355L418 250L522 145Q606 61 618 48T630 29Z"></path></g><g data-mml-node="msup" transform="translate(6222.9,0)"><g data-mml-node="mn"><path data-c="31" d="M213 578L200 573Q186 568 160 563T102 556H83V602H102Q149 604 189 617T245 641T273 663Q275 666 285 666Q294 666 302 660V361L303 61Q310 54 315 52T339 48T401 46H427V0H416Q395 3 257 3Q121 3 100 0H88V46H114Q136 46 152 46T177 47T193 50T201 52T207 57T213 61V578Z"></path><path data-c="30" d="M96 585Q152 666 249 666Q297 666 345 640T423 548Q460 465 460 320Q460 165 417 83Q397 41 362 16T301 -15T250 -22Q224 -22 198 -16T137 16T82 83Q39 165 39 320Q39 494 96 585ZM321 597Q291 629 250 629Q208 629 178 597Q153 571 145 525T137 333Q137 175 145 125T181 46Q209 16 250 16Q290 16 318 46Q347 76 354 130T362 333Q362 478 354 524T321 597Z" transform="translate(500,0)"></path></g><g data-mml-node="mn" transform="translate(1033,393.1) scale(0.707)"><path data-c="39" d="M352 287Q304 211 232 211Q154 211 104 270T44 396Q42 412 42 436V444Q42 537 111 606Q171 666 243 666Q245 666 249 666T257 665H261Q273 665 286 663T323 651T370 619T413 560Q456 472 456 334Q456 194 396 97Q361 41 312 10T208 -22Q147 -22 108 7T68 93T121 149Q143 149 158 135T173 96Q173 78 164 65T148 49T135 44L131 43Q131 41 138 37T164 27T206 22H212Q272 22 313 86Q352 142 352 280V287ZM244 248Q292 248 321 297T351 430Q351 508 343 542Q341 552 337 562T323 588T293 615T246 625Q208 625 181 598Q160 576 154 546T147 441Q147 358 152 329T172 282Q197 248 244 248Z"></path></g></g><g data-mml-node="TeXAtom" data-mjx-texclass="ORD" transform="translate(7659.4,0)"><g data-mml-node="mo"><path data-c="2F" d="M423 750Q432 750 438 744T444 730Q444 725 271 248T92 -240Q85 -250 75 -250Q68 -250 62 -245T56 -231Q56 -221 230 257T407 740Q411 750 423 750Z"></path></g></g><g data-mml-node="mi" transform="translate(8159.4,0)"><path data-c="1D43F" d="M228 637Q194 637 192 641Q191 643 191 649Q191 673 202 682Q204 683 217 683Q271 680 344 680Q485 680 506 683H518Q524 677 524 674T522 656Q517 641 513 637H475Q406 636 394 628Q387 624 380 600T313 336Q297 271 279 198T252 88L243 52Q243 48 252 48T311 46H328Q360 46 379 47T428 54T478 72T522 106T564 161Q580 191 594 228T611 270Q616 273 628 273H641Q647 264 647 262T627 203T583 83T557 9Q555 4 553 3T537 0T494 -1Q483 -1 418 -1T294 0H116Q32 0 32 10Q32 17 34 24Q39 43 44 45Q48 46 59 46H65Q92 46 125 49Q139 52 144 61Q147 65 216 339T285 628Q285 635 228 637Z"></path></g></g></g></svg></mjx-container></li> -<li>异常情况:<ul> +<li>异常情况: +<ul> <li>升高: 原发性血小板增多症, 真性红细胞增多症, 慢性白血病, 症状性血小板增多症, 感染, 炎症, 恶性肿瘤, 缺铁性贫血, 外伤, 手术, 出血等</li> <li>降低: 原发性血小板减少性紫癜, 播散性红斑狼疮, 药物过敏性血小板减少症, 弥漫性血管内凝血, 血小板破坏增多, 血小板生成减少等</li> </ul> @@ -5330,7 +5938,8 @@ await prisma.$transaction(async tx => { <entry> <title>西柚对药物的影响</title> <url>/2024/11/15/%E8%A5%BF%E6%9F%9A%E5%AF%B9%E8%8D%AF%E7%89%A9%E7%9A%84%E5%BD%B1%E5%93%8D/</url> - <content><![CDATA[<p>西柚,橙子之类中的呋喃香豆素会抑制肝脏中 CYP3A4 酶的活性,经肝脏代谢的药物,正常是肝脏中的酶在发挥作用,CYP3A4 酶就是其中一种,吃药的同时又吃了西柚相当于无形中增加了药物剂量,曾经有人吃硝苯地平的同时,喝了大概 500mL 的西柚汁,结果血压迅速下降导致了危险。<br>除此之外这种酶参与了现今使用近半数药物的代谢,总体来说,呋喃香豆素可以使药物以 2~10 倍的量进入血液,目前已知的,有超过 85 种药物会受到西柚的影响,但药物种类实在太多了,很难找到会受西柚影响的完整药物名单。最稳妥的方案还是吃药的时候别他妈吃西柚了</p> + <content><![CDATA[<p>西柚,橙子之类中的呋喃香豆素会抑制肝脏中 CYP3A4 酶的活性,经肝脏代谢的药物,正常是肝脏中的酶在发挥作用,CYP3A4 酶就是其中一种,吃药的同时又吃了西柚相当于无形中增加了药物剂量,曾经有人吃硝苯地平的同时,喝了大概 500mL 的西柚汁,结果血压迅速下降导致了危险。<br> +除此之外这种酶参与了现今使用近半数药物的代谢,总体来说,呋喃香豆素可以使药物以 2~10 倍的量进入血液,目前已知的,有超过 85 种药物会受到西柚的影响,但药物种类实在太多了,很难找到会受西柚影响的完整药物名单。最稳妥的方案还是吃药的时候别他妈吃西柚了</p> ]]></content> <tags> <tag>Medicine</tag> @@ -6638,9 +7247,8 @@ await prisma.$transaction(async tx => { <entry> <title>隐藏一些OCaml Effect的机制,让其语法在精神上更接近delimcc</title> <url>/2023/06/28/%E9%9A%90%E8%97%8F%E4%B8%80%E4%BA%9BOCaml-Effect%E7%9A%84%E6%9C%BA%E5%88%B6%EF%BC%8C%E8%AE%A9%E5%85%B6%E8%AF%AD%E6%B3%95%E5%9C%A8%E7%B2%BE%E7%A5%9E%E4%B8%8A%E6%9B%B4%E6%8E%A5%E8%BF%91delimcc/</url> - <content><![CDATA[<p><a href="https://github.com/kayceesrk/delimcc_of_fxhandler">delimcc_of_fxhandler这个库</a>在OCaml5的effect handlers上实现了一些delimcc原语(shift/reset, control/prompt这些):</p> + <content><![CDATA[<p><a href="https://github.com/kayceesrk/delimcc_of_fxhandler">delimcc_of_fxhandler这个库</a>在OCaml5的effect handlers上实现了一些delimcc原语(shift/reset, control/prompt这些):</p> <figure class="highlight ocaml"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> p = new_prompt <span class="literal">()</span> <span class="keyword">in</span></span><br><span class="line"><span class="keyword">assert</span> (<span class="literal">[]</span> = push_prompt p (<span class="keyword">fun</span> <span class="literal">()</span> -></span><br><span class="line"> <span class="number">1</span>::<span class="number">2</span>::take_subcont p (<span class="keyword">fun</span> _k -> <span class="literal">[]</span>)));</span><br><span class="line"><span class="keyword">assert</span> ([<span class="number">1</span>;<span class="number">2</span>] = push_prompt p (<span class="keyword">fun</span> <span class="literal">()</span> -></span><br><span class="line"> <span class="number">1</span>::<span class="number">2</span>::take_subcont p (<span class="keyword">fun</span> k -> push_subcont k <span class="literal">[]</span>)));</span><br><span class="line"><span class="keyword">assert</span> (<span class="number">135</span> =</span><br><span class="line"> <span class="keyword">let</span> p1 = new_prompt <span class="literal">()</span> <span class="keyword">in</span></span><br><span class="line"> <span class="keyword">let</span> p2 = new_prompt <span class="literal">()</span> <span class="keyword">in</span></span><br><span class="line"> <span class="keyword">let</span> p3 = new_prompt <span class="literal">()</span> <span class="keyword">in</span></span><br><span class="line"> <span class="keyword">let</span> pushtwice sk =</span><br><span class="line"> sk (<span class="keyword">fun</span> <span class="literal">()</span> -></span><br><span class="line"> sk (<span class="keyword">fun</span> <span class="literal">()</span> -></span><br><span class="line"> shift0 p2 (<span class="keyword">fun</span> sk2 -> sk2 (<span class="keyword">fun</span> <span class="literal">()</span> -></span><br><span class="line"> sk2 (<span class="keyword">fun</span> <span class="literal">()</span> -> <span class="number">3</span>))) <span class="literal">()</span>))</span><br><span class="line"> <span class="keyword">in</span></span><br><span class="line"> push_prompt p1 (<span class="keyword">fun</span> <span class="literal">()</span> -></span><br><span class="line"> push_prompt p2 (<span class="keyword">fun</span> <span class="literal">()</span> -></span><br><span class="line"> push_prompt p3 (<span class="keyword">fun</span> <span class="literal">()</span> -> shift0 p1 pushtwice <span class="literal">()</span>) + <span class="number">10</span>) + <span class="number">1</span>) + <span class="number">100</span>);</span><br><span class="line"></span><br><span class="line">print_endline <span class="string">"Success!"</span></span><br></pre></td></tr></table></figure> - <p>另外, <a href="https://github.com/avsm/ocaml/commits/effect-syntax">avsm这里</a>可以看到一些OCaml的Effect Syntax进展。</p> <p>还有 <a href="https://github.com/dhil/ocaml-multicont">multi-shot continuations in OCaml</a>,在这个仓库里面还讨论了一些有趣的问题,例如,OCaml 编译器和runtime会做出一些假设从而进行一些优化,这些优化在使用multi-shot continutation时是不可取的(或完全错误的)。编译器优化导致错误的一个例子是堆到栈的转换,例如:</p> <figure class="highlight ocaml"><table><tr><td class="code"><pre><span class="line"><span class="comment">(* An illustration of how the heap to stack optimisation is broken.</span></span><br><span class="line"><span class="comment"> * This example is adapted from de Vilhena and Pottier (2021).</span></span><br><span class="line"><span class="comment"> * file: heap2stack.ml</span></span><br><span class="line"><span class="comment"> * compile: ocamlopt -I $(opam var lib)/multicont multicont.cmxa heap2stack.ml</span></span><br><span class="line"><span class="comment"> * run: ./a.out *)</span></span><br><span class="line"></span><br><span class="line"><span class="comment">(* We first require a little bit of setup. The following declares an</span></span><br><span class="line"><span class="comment"> operation `Twice' which we use to implement multiple returns. *)</span></span><br><span class="line"><span class="keyword">type</span> _ <span class="type">Effect</span>.t += <span class="type">Twice</span> : <span class="built_in">unit</span> <span class="type">Effect</span>.t</span><br><span class="line"></span><br><span class="line"><span class="comment">(* The handler `htwice' interprets `Twice' by simply invoking its</span></span><br><span class="line"><span class="comment"> continuation twice. *)</span></span><br><span class="line"><span class="keyword">let</span> htwice : (<span class="built_in">unit</span>, <span class="built_in">unit</span>) <span class="type">Effect</span>.<span class="type">Deep</span>.handler</span><br><span class="line"> = { retc = (<span class="keyword">fun</span> x -> x)</span><br><span class="line"> ; exnc = (<span class="keyword">fun</span> e -> raise e)</span><br><span class="line"> ; effc = (<span class="keyword">fun</span> (<span class="keyword">type</span> a) (eff : a <span class="type">Effect</span>.t) -></span><br><span class="line"> <span class="keyword">let</span> <span class="keyword">open</span> <span class="type">Effect</span>.<span class="type">Deep</span> <span class="keyword">in</span></span><br><span class="line"> <span class="keyword">match</span> eff <span class="keyword">with</span></span><br><span class="line"> | <span class="type">Twice</span> -> <span class="type">Some</span> (<span class="keyword">fun</span> (k : (a, _) continuation) -></span><br><span class="line"> continue (<span class="type">Multicont</span>.<span class="type">Deep</span>.clone_continuation k) <span class="literal">()</span>;</span><br><span class="line"> continue k <span class="literal">()</span>)</span><br><span class="line"> | _ -> <span class="type">None</span>) }</span><br><span class="line"></span><br><span class="line"><span class="comment">(* Now for the interesting stuff. In the code below, the compiler will</span></span><br><span class="line"><span class="comment"> perform an escape analysis on the reference `i' and deduce that it</span></span><br><span class="line"><span class="comment"> does not escape the local scope, because it is unaware of the</span></span><br><span class="line"><span class="comment"> semantics of `perform Twice', hence the optimiser will transform</span></span><br><span class="line"><span class="comment"> `i' into an immediate on the stack to save a heap allocation. As a</span></span><br><span class="line"><span class="comment"> consequence, the assertion `(!i = 1)' will succeed twice, whereas</span></span><br><span class="line"><span class="comment"> it should fail after the second return of `perform Twice'. *)</span></span><br><span class="line"><span class="keyword">let</span> heap2stack <span class="literal">()</span> =</span><br><span class="line"> <span class="type">Effect</span>.<span class="type">Deep</span>.match_with</span><br><span class="line"> (<span class="keyword">fun</span> <span class="literal">()</span> -></span><br><span class="line"> <span class="keyword">let</span> i = <span class="built_in">ref</span> <span class="number">0</span> <span class="keyword">in</span></span><br><span class="line"> <span class="type">Effect</span>.perform <span class="type">Twice</span>;</span><br><span class="line"> i := !i + <span class="number">1</span>;</span><br><span class="line"> <span class="type">Printf</span>.printf <span class="string">"i = %d\n%!"</span> !i;</span><br><span class="line"> <span class="keyword">assert</span> (!i = <span class="number">1</span>))</span><br><span class="line"> <span class="literal">()</span> htwice</span><br><span class="line"></span><br><span class="line"><span class="comment">(* The following does not trigger an assertion failure. *)</span></span><br><span class="line"><span class="keyword">let</span> _ = heap2stack <span class="literal">()</span></span><br><span class="line"></span><br><span class="line"><span class="comment">(* To fix this issue, we can wrap reference allocations in an instance</span></span><br><span class="line"><span class="comment"> of `Sys.opaque_identity'. However, this is not really a viable fix</span></span><br><span class="line"><span class="comment"> in general, as we may not have access to the client code that</span></span><br><span class="line"><span class="comment"> allocates the reference! *)</span></span><br><span class="line"><span class="keyword">let</span> heap2stack' <span class="literal">()</span> =</span><br><span class="line"> <span class="type">Effect</span>.<span class="type">Deep</span>.match_with</span><br><span class="line"> (<span class="keyword">fun</span> <span class="literal">()</span> -></span><br><span class="line"> <span class="keyword">let</span> i = <span class="type">Sys</span>.opaque_identity (<span class="built_in">ref</span> <span class="number">0</span>) <span class="keyword">in</span></span><br><span class="line"> <span class="type">Effect</span>.perform <span class="type">Twice</span>;</span><br><span class="line"> i := !i + <span class="number">1</span>;</span><br><span class="line"> <span class="type">Printf</span>.printf <span class="string">"i = %d\n%!"</span> !i;</span><br><span class="line"> <span class="keyword">assert</span> (!i = <span class="number">1</span>))</span><br><span class="line"> <span class="literal">()</span> htwice</span><br><span class="line"></span><br><span class="line"><span class="comment">(* The following triggers an assertion failure. *)</span></span><br><span class="line"><span class="keyword">let</span> _ = heap2stack' <span class="literal">()</span></span><br></pre></td></tr></table></figure> @@ -6667,7 +7275,6 @@ await prisma.$transaction(async tx => { </ul> <p>用 F# 来描述,以订单管理为例,大概写一下:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">type</span> <span class="title class_">OrderStatus</span> <span class="operator">=</span> </span><br><span class="line"> <span class="operator">|</span> New</span><br><span class="line"> <span class="operator">|</span> Shipped</span><br><span class="line"> <span class="operator">|</span> Delivered</span><br><span class="line"> <span class="operator">|</span> Cancelled</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">OrderItem</span> (productName<span class="operator">:</span> <span class="type">string</span>, price<span class="operator">:</span> <span class="type">float</span>, quantity<span class="operator">:</span> <span class="type">int</span>) <span class="operator">=</span> </span><br><span class="line"> <span class="keyword">do</span></span><br><span class="line"> <span class="keyword">if</span> quantity <span class="operator"><=</span> <span class="number">0</span> <span class="keyword">then</span></span><br><span class="line"> <span class="built_in">failwith</span> <span class="string">"Quantity must be positive"</span></span><br><span class="line"> </span><br><span class="line"> <span class="keyword">member</span> <span class="keyword">public</span> this.ProductName <span class="operator">=</span> productName</span><br><span class="line"> <span class="keyword">member</span> <span class="keyword">public</span> this.Price <span class="operator">=</span> price</span><br><span class="line"> <span class="keyword">member</span> <span class="keyword">public</span> this.Quantity <span class="operator">=</span> quantity</span><br><span class="line"> <span class="keyword">member</span> <span class="keyword">public</span> this.TotalPrice () <span class="operator">=</span> price <span class="operator">*</span> quantity</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">Order</span> (<span class="built_in">id</span><span class="operator">:</span> <span class="type">int</span>, customerName<span class="operator">:</span> <span class="type">string</span>) <span class="operator">=</span> </span><br><span class="line"> <span class="keyword">let</span> <span class="keyword">mutable</span> status <span class="operator">=</span> OrderStatus.New</span><br><span class="line"> <span class="keyword">let</span> <span class="keyword">mutable</span> orderItems <span class="operator">=</span> []</span><br><span class="line"></span><br><span class="line"> <span class="keyword">member</span> <span class="keyword">public</span> this.Id <span class="operator">=</span> <span class="built_in">id</span></span><br><span class="line"> <span class="keyword">member</span> <span class="keyword">public</span> this.CustomerName <span class="operator">=</span> customerName</span><br><span class="line"> <span class="keyword">member</span> <span class="keyword">public</span> this.Status <span class="operator">=</span> status</span><br><span class="line"> <span class="keyword">member</span> <span class="keyword">public</span> this.OrderItems <span class="operator">=</span> orderItems</span><br><span class="line"></span><br><span class="line"> <span class="keyword">member</span> <span class="keyword">public</span> this.AddItem (item<span class="operator">:</span> OrderItem, price<span class="operator">:</span> <span class="type">float</span>, quantity<span class="operator">:</span> <span class="type">int</span>) <span class="operator">=</span></span><br><span class="line"> <span class="keyword">if</span> quantity <span class="operator"><=</span> <span class="number">0</span> <span class="keyword">then</span></span><br><span class="line"> <span class="built_in">failwith</span> <span class="string">"Quantity must be positive"</span></span><br><span class="line"> </span><br><span class="line"> orderItems <span class="operator"><-</span> orderItems <span class="operator">@</span> [OrderItem(item.ProductName, price, quantity)]</span><br><span class="line"></span><br><span class="line"> <span class="keyword">member</span> <span class="keyword">public</span> this.ChangeStatus (status<span class="operator">:</span> OrderStatus) <span class="operator">=</span></span><br><span class="line"> this.Status <span class="operator"><-</span> status</span><br><span class="line"></span><br><span class="line"> <span class="keyword">member</span> <span class="keyword">public</span> this.TotalPrice () <span class="operator">=</span></span><br><span class="line"> orderItems <span class="operator">|></span> List.sumBy (<span class="keyword">fun</span> item <span class="operator">-></span> item.TotalPrice())</span><br><span class="line"></span><br><span class="line"> <span class="keyword">member</span> <span class="keyword">public</span> this.GetTotalPrice () <span class="operator">=</span></span><br><span class="line"> orderItems <span class="operator">|></span> List.sumBy (<span class="keyword">fun</span> item <span class="operator">-></span> item.TotalPrice())</span><br></pre></td></tr></table></figure> - <p>在这个例子中,<code>Order</code> 是聚合根,它通过 <code>AddItem</code> 方法来添加订单项,保证每个订单项符合业务规则。同时,聚合根 <code>Order</code> 还负责订单状态的管理,例如通过 <code>ChangeStatus</code> 方法来更新订单状态。<code>OrderItem</code> 是聚合内的一个实体,表示订单项,它通过 <code>GetTotalPrice</code> 方法来计算每个订单项的总价。外部系统只能通过 <code>Order</code> 聚合根来访问和操作订单项,而不能直接访问或修改 <code>OrderItem</code></p> ]]></content> <tags> @@ -6679,7 +7286,6 @@ await prisma.$transaction(async tx => { <url>/2025/03/19/%E9%A2%86%E5%9F%9F%E9%A9%B1%E5%8A%A8%E8%AE%BE%E8%AE%A1%E4%B8%AD%E8%81%9A%E5%90%88%E6%A0%B9%E6%8C%81%E4%B9%85%E5%8C%96%E5%92%8C%E4%BA%8B%E4%BB%B6%E5%8F%91%E5%B8%83%E5%8F%AF%E8%83%BD%E5%AF%BC%E8%87%B4%E6%95%B0%E6%8D%AE%E4%B8%8D%E4%B8%80%E8%87%B4%E9%97%AE%E9%A2%98/</url> <content><![CDATA[<p>使用领域事件的一种直接做法是:在 应用服务 (Application Service) 中产生事件并发布出去。例如,对于“用户昵称更新”的场景来讲,对应的应用服务 <code>UserCommandService</code> 实现如下:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">member</span> <span class="keyword">public</span> this.UpdateMyName (command<span class="operator">:</span> UpdateUsernameCommand) (user<span class="operator">:</span> User) <span class="operator">=</span></span><br><span class="line"> <span class="keyword">let</span> user <span class="operator">=</span> userRepository.GetById user.Id</span><br><span class="line"> <span class="keyword">let</span> oldName <span class="operator">=</span> user.Username</span><br><span class="line"> <span class="keyword">let</span> newName <span class="operator">=</span> command.Username</span><br><span class="line"></span><br><span class="line"> user.UpdateUsername newName</span><br><span class="line"> <span class="operator">|></span> userRepository.Save</span><br><span class="line"> </span><br><span class="line"> UsernameChangeEvent (user.Id, newName, oldName) </span><br><span class="line"> <span class="operator">|></span> eventPublisher.Publish</span><br></pre></td></tr></table></figure> - <p>这里,在更新了用户姓名之后,即刻调用事件发布器 <code>eventPublisher.Publish</code> 将事件发送到消息队列中。虽然这种方式比较流行,但它至少存在两个问题:</p> <ol> <li>领域事件本应属于领域模型的一部分,也即应该从领域模型中产生,而这里却在应用服务中产生</li> @@ -6687,24 +7293,19 @@ await prisma.$transaction(async tx => { </ol> <p>对于第1个问题,可以采用“从领域模型中返回领域事件”的方式:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">member</span> <span class="keyword">public</span> this.UpdateMyName (command<span class="operator">:</span> UpdateUsernameCommand) (user<span class="operator">:</span> User) <span class="operator">=</span></span><br><span class="line"> <span class="keyword">let</span> user <span class="operator">=</span> userRepository.GetById user.Id</span><br><span class="line"> <span class="keyword">let</span> oldName <span class="operator">=</span> user.Username</span><br><span class="line"> <span class="keyword">let</span> newName <span class="operator">=</span> command.Username</span><br><span class="line"></span><br><span class="line"> user.UpdateUsername newName <span class="comment">// UpdateUsername 中构建 UsernameChangeEvent</span></span><br><span class="line"> <span class="operator">|></span> <span class="keyword">fun</span> user event <span class="operator">-></span> </span><br><span class="line"> userRepository.Save user</span><br><span class="line"> eventPublisher.Publish event</span><br></pre></td></tr></table></figure> - <p>这种方式保证了领域事件是从领域模型中产生,但仍然存在第二个问题。</p> <p>第二个问题中所谓的“数据一致性”,表示的是将聚合根保存到数据库和将领域事件发布到消息队列之间的一致性。由于数据库和消息队列属于异构的数据源,要保证他们之间的数据一致性需要引入分布式事务。</p> <p>但是分布式事务通常是比较重量级的,再加上当下的诸多常见消息队列均不支持分布式事务(比如Kafka),因此并不建议使用分布式事务来解决这个问题。</p> <p><a href="https://microservices.io/patterns/data/transactional-outbox.html">Transactional Outbox</a> 便是一种方案,概括来说,这种方式将一个分布式事务的问题拆解为多个本地事务,并采用“至少一次投递(At Least Once Delivery)”原则保证消息的发布。具体来讲,发布方在与业务数据相同的数据库中为领域事件创建相应的事件发布表(Outbox table),然后在保存业务数据的同时将所产生的事件保存到事件发布表中,由于此时二者都属于同一个数据库的本地事务所管辖,因此保证了“业务操作”与“事件产生”之间的一致性。此时的代码变成了:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">member</span> <span class="keyword">public</span> this.UpdateMyName (command<span class="operator">:</span> UpdateUsernameCommand) (user<span class="operator">:</span> User) <span class="operator">=</span></span><br><span class="line"> <span class="keyword">let</span> user <span class="operator">=</span> userRepository.GetById user.Id</span><br><span class="line"> <span class="keyword">let</span> oldName <span class="operator">=</span> user.Username</span><br><span class="line"> <span class="keyword">let</span> newName <span class="operator">=</span> command.Username</span><br><span class="line"></span><br><span class="line"> user.UpdateUsername newName <span class="comment">// UpdateUsername 中构建 UsernameChangeEvent</span></span><br><span class="line"> <span class="operator">|></span> <span class="keyword">fun</span> user event <span class="operator">-></span> </span><br><span class="line"> userRepository.Save user</span><br><span class="line"> eventStore.Save event <span class="comment">// 这儿用 eventStore 代替 eventPublisher 啦</span></span><br></pre></td></tr></table></figure> - <p>应用服务不再将事件直接发布出去,而是将事件保存到数据库中,之后,另一个模块将从数据库中读取事件并发布。</p> <p>然而,这种方式依然有个缺点:每个需要产生领域事件的场景都需要应用服务先后调用<code>repository.Save()</code>和<code>eventStore.Save()</code>,导致了代码重复。解决方法也很简单——在聚合根中临时保存领域事件,然后在资源库中同时保存聚合根和领域事件到数据库。</p> <p>在这种方式下,首先需要在聚合根的基类中完成与领域事件相关的各种设施,包括创建临时性的事件容器<code>events</code>以及通用的事件产生方法<code>RaiseEvent()</code>:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="meta">[<AbstractClass>]</span></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">IAggregateRoot</span> <span class="operator">=</span> </span><br><span class="line"> <span class="operator">...</span></span><br><span class="line"> <span class="keyword">let</span> events <span class="operator">=</span> Collections.Generic.List<span class="operator"><</span>DomainEvent<span class="operator">></span> ()</span><br><span class="line"></span><br><span class="line"> <span class="keyword">member</span> <span class="keyword">private</span> this.RaiseEvent (event<span class="operator">:</span> DomainEvent) <span class="operator">=</span></span><br><span class="line"> events.Add event</span><br><span class="line"> </span><br><span class="line"> <span class="operator">...</span></span><br></pre></td></tr></table></figure> - <p>在聚合根基类<code>AggregateRoot</code>中,<code>events</code>字段用于临时保存聚合根中所产生的所有事件,各实际的聚合根类通过调用<code>RaiseEvent()</code>向<code>events</code>中添加事件。比如,对于“用户修改昵称”而言,<code>User</code>实现如下:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">member</span> <span class="keyword">public</span> this.UpdateUsername (name<span class="operator">:</span> <span class="type">string</span>, user<span class="operator">:</span> User) <span class="operator">=</span></span><br><span class="line"> <span class="keyword">if</span> this.Username <span class="operator">=</span> name <span class="keyword">then</span></span><br><span class="line"> ()</span><br><span class="line"> <span class="keyword">else</span></span><br><span class="line"> <span class="keyword">let</span> oldName <span class="operator">=</span> this.Username</span><br><span class="line"> this.Username <span class="operator"><-</span> name</span><br><span class="line"> UsernameChangeEvent (user.Id, name, oldName) </span><br><span class="line"> <span class="operator">|></span> this.RaiseEvent</span><br></pre></td></tr></table></figure> - <p>这里,聚合根 <code>User</code> 不再返回领域事件,而是将领域事件通过<code>AggregateRoot.RaiseEvent()</code>暂时性地保存到自身的<code>events</code>中。之后在保存<code>User</code>时,资源库的公共基类<code>BaseRepository</code>的<code>Save()</code>方法同时完成对聚合根和领域事件的持久化:</p> <figure class="highlight fsharp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">member</span> <span class="keyword">public</span> this.Save<span class="operator"><</span>AR<span class="operator">:</span> <span class="keyword">when</span> AR <span class="operator">:></span> AggrateRoot<span class="operator">></span> (it<span class="operator">:</span> AR) <span class="operator">=</span></span><br><span class="line"> <span class="keyword">match</span> it <span class="keyword">with</span></span><br><span class="line"> <span class="operator">|</span> <span class="literal">null</span> <span class="operator">-></span> <span class="built_in">failwith</span> <span class="string">"..."</span></span><br><span class="line"> <span class="operator">|</span> it <span class="keyword">when</span> it.Events <span class="operator">|></span> isEmpty <span class="operator">|></span> <span class="built_in">not</span> <span class="operator">-></span> </span><br><span class="line"> this.SaveEvents it.Events</span><br><span class="line"> this.CleanEvents ()</span><br><span class="line"> <span class="operator">|</span> _ <span class="operator">-></span> ()</span><br><span class="line"></span><br><span class="line"> db.Save it</span><br></pre></td></tr></table></figure> - <p>在<code>Save()</code>方法中,首先获取到聚合根中的所有领域事件,然后通过<code>SaveEvents()</code>方法将它们保存到发布事件表中,最后通过<code>db.Save it</code>保存聚合根。需要注意的是,在这种方式下,<code>AggregateRoot</code>中的<code>events</code>字段是不能被持久化的,因为需要保证每次从数据库中加载出聚合根时<code>events</code>都是空的,为此在<code>SaveEvents()</code>保存了领域事件后,立即调用<code>it.clearEvents()</code>将所有的领域事件清空掉,以免领域事件随着聚合根一道被持久化到数据库中。</p> <p>到目前为止,对领域事件的处理都还没有涉及到与任何消息中间件相关的内容,也即事件的产生是一个完全独立于消息队列的关注点,此时不用关心领域事件之后将以何种形式发布出去,Kafka 也好,RabbitMQ 也罢。除了关注点分离的好处外,这种解耦也使得系统在有可能切换消息中间件时更加的简单。</p> <p>对于“在应用服务中通过<code>eventPublisher.Publish()</code>直接发布事件”而言,事件的产生和发布是同时完成的;但是对于“在聚合根中临时性保存领域事件”的方式来说,它只解决了事件的产生问题,并未解决事件的发布问题,事件的发布方应该采用“发射后不管(Fire And Forget)”的原则,即发布方无需了解消费方是如何处理领域事件的,甚至都不需要知道事件被哪些消费方所消费。</p> @@ -6724,7 +7325,8 @@ await prisma.$transaction(async tx => { <entry> <title>关于我</title> <url>/about.html</url> - <content><![CDATA[<h2 id="韩暮秋"><a href="#韩暮秋" class="headerlink" title="韩暮秋"></a>韩暮秋</h2><ul> + <content><![CDATA[<h2 id="韩暮秋"><a class="header-anchor" href="#韩暮秋">¶</a>韩暮秋</h2> +<ul> <li>Github: <a href="https://github.com/muqiuhan">https://github.com/muqiuhan</a></li> <li>QQ群: <a href="http://qm.qq.com/cgi-bin/qm/qr?_wv%253D1027%2526k%253DAdCEKMDgAUg2ppuYqPt-OUeXBUG_jFN0%2526authKey%253D4%252FlDBj2jxzc32hN756pW2wlDkaNR%252FqrstHr6hsIy%252B6pfeRnvPvS7QBMUgeQfkp2V%2526noverify%253D0%2526group_code%253D780653172">780653172</a></li> <li>邮箱: <a href="[email protected]">[email protected]</a></li> |
