在F#中创建具有多个浮点测量单位的列表 [英] Creating a list with multiple units of measurements of floats in F#

查看:86
本文介绍了在F#中创建具有多个浮点测量单位的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我试图以各种方式解决此问题,但我无法完成这项工作.

So, I've tried to get around this in various ways, but I just can't make this work.

有没有办法制作一个包含不同计量单位(全部基于浮点数)的值的列表?例如:

Is there any way to make a list that contains values of varying units of measurement (all based on floats)? For example:

let myList = [0.07<ms>; 0.9; 7.2<mm>;]

由于它们被视为不同类型,因此不能将它们放在同一列表中.我尝试将列表声明为let myList : float<_> list = ...,并为无量纲数字提供了度量单位,但仍然出现输入错误:期望float<'u>但得到float.

As they are treated as different types, you cannot put them in the same list. I tried declaring the list as let myList : float<_> list = ..., and giving dimensionless numbers a unit of measurement, but I still got a typing error: expecting float<'u> but got float.

我无法使用元组/n-ple,因为我不知道列表中将包含多少个值.

I am unable to use a tuple/n-ple as I do not know the number of values that will be in the list.

我对F#还是陌生的,花了相当长的时间在存储上搜索文档和Web,但是还没有找到解决方案.如果有人能指出正确的方向,我将不胜感激.谢谢!

I am quite new to F# and have spent quite a while scouring the documents and web on storage, but haven't found a solution. If anyone could point me in the right direction, I would really appreciate it. Thank you!

推荐答案

我认为您需要给出一个更长的示例,以显示您要如何使用此列表.否则,很难给出一个好的答案,因为这取决于用途.

I think you'll need to give a longer example that shows how you want to use this list. Otherwise it is difficult to give a good answer, because it depends on the use.

如果您只想创建代表不同事物的数字列表,则可以考虑使用有区别的并集来区分它们:

If you just want to create a list of numbers that represent different things, then you can consider using a discriminated union to differentiate between them:

type Numeric =
  | Length of float<mm>
  | Time of float<ms>
  | Unitless of float

let myList = [ Time 0.07<ms>; Unitless 0.9; Length 7.2<mm>;]

然后,您可以创建一个包含不同数字(具有不同物理含义)的列表.遍历列表时,您需要使用模式匹配来提取值.

Then you can create a list that contains different numbers (with different physical meanings). When iterating over the list, you'll need to use pattern matching to extract the value.

或者,您可以在创建列表时删除所有单位,但是随后失去了计量单位提供的保证(这意味着当您从列表中获得一些价值时,您将不知道它拥有什么单位,而您可能会错误地解释它):

Alternatively, you can just drop all units when creating the list, but then you lose the guarantees provided by units of measure (meaning that when you get some value from the list, you won't know what unit it had and you could interpret it wrongly):

let myList = [ float 0.07<ms>; 0.9; float 7.2<mm>;]

您还可以使用一个F#库,通过该库,您可以在运行时跟踪单位.

这篇关于在F#中创建具有多个浮点测量单位的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆