简体   繁体   中英

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

I am using F# Canopy to complete some web testing. 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. 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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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