简体   繁体   English

F#Canopy - 生成随机字母和/或数字并在变量中使用

[英]F# Canopy - Generate Random Letters and or Numbers and use in a variable

I am using F# Canopy to complete some web testing. 我正在使用F#Canopy来完成一些网络测试。 I am trying to create and load a random number with or without letters, not that important and use it to paste to my website. 我正在尝试使用或不使用字母创建和加载随机数,这并不重要,并使用它粘贴到我的网站。

The code I am currently using is 我目前使用的代码是

let genRandomNumbers count =
    let rnd = System.Random()
    List.init count 

let l = genRandomNumbers 1

"#CompanyName" << l()

The #CompanyName is the ID of the element I am trying to pass l into. #CompanyName是我试图传入l的元素的ID。 As it stands I am receiving the error 'The expression was expected to have type string but here it has type a list. 现在我收到错误'表达式应该有类型字符串,但在这里它键入一个列表。

Any help would be greatly appreciated. 任何帮助将不胜感激。

The << operator in canopy writes a string to the selector (I haven't used it but the documentation looks pretty clear), but your function returns a list. canopy中<<运算符将一个字符串写入选择器(我没有使用它,但文档看起来很清楚),但是你的函数返回一个列表。 If you want the random string to work, you could do something like this (not tested code) 如果你想随机字符串工作,你可以做这样的事情(没有经过测试的代码)

let randomNumString n = genRandomNumbers n |> List.map string |> List.reduce (+)

This maps your random list to strings then concats all the strings together using the first element as the accumulator seed. 这将您的随机列表映射到字符串,然后使用第一个元素作为累加器种子将所有字符串连接在一起。 You could also do a fold 你也可以做一个折叠

let randomNumString n = genRandomNumbers n
                         |> List.fold (fun acc i -> acc + (string i)) "" 

Putting it all together 把它们放在一起

let rand = new System.Random()

let genRandomNumbers count = List.init count (fun _ -> rand.Next())

let randomNumString n = genRandomNumbers n |> List.map string |> List.reduce (+)

"#CompanyName" << (randomNumString 1)

In general, F# won't do any type promotion for you. 一般来说,F#不会为您做任何类型的促销活动。 Since the << operator wants a string on the right hand side, you need to map your list to a string somehow. 由于<<运算符需要右侧的字符串,因此您需要以某种方式将列表映射到字符串。 That means iterating over each element, converting the number to a string, and adding all the elements together into one final string. 这意味着迭代每个元素,将数字转换为字符串,并将所有元素一起添加到一个最终字符串中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM