[英]How do I translate this Haskell to F#?
I'm trying to learn F# by translating some Haskell code I wrote a very long time ago, but I'm stuck!我试图通过翻译我很久以前写的一些 Haskell 代码来学习 F#,但我被卡住了!
percent :: Int -> Int -> Float
percent a b = (fromInt a / fromInt b) * 100
freqs :: String -> [Float]
freqs ws = [percent (count x ws) (lowers ws) | x <- ['a' .. 'z']]
I've managed this:我已经做到了:
let percent a b = (float a / float b) * 100.
although i dont like having to have the .虽然我不喜欢必须拥有 . after the 100.
100 之后。
What is the name of the operation I am performing in freqs
, and how do I translate it to F#?我在
freqs
执行的操作的名称是什么,如何将其转换为 F#?
Edit: count
and lowers
are Char -> String -> Int
and String -> Int
respectively, and I have translated these already.编辑:
count
和lowers
分别是Char -> String -> Int
和String -> Int
,我已经翻译了这些。
This is a list comprehension, and in F# it looks like the last two lines below:这是一个列表推导式,在 F# 中它看起来像下面的最后两行:
// stub out since don't know the implementation
let count (c:char) (s:string) = 4
let lowers (s:string) = 10
// your code
let percent a b = (float a / float b) * 100.
let freq ws = [for x in ['a'..'z'] do
yield percent (count x ws) (lowers ws)]
More generally I think Haskell list comprehensions have the form suggested by the example below, and the corresponding F# is shown.更一般地说,我认为 Haskell 列表推导式具有以下示例建议的形式,并显示了相应的 F#。
// Haskell
// [e(x,y) | x <- l1, y <- l2, pred(x,y)]
// F#
[for x in l1 do
for y in l2 do
if pred(x,y) then
yield e(x,y)]
Note that Brian's F# code:请注意,Brian 的 F# 代码:
let freq ws = [for x in ['a'..'z'] do yield percent (count x ws) (lowers ws)]
Can be written more elegantly as:可以更优雅地写成:
let freq ws = [for x in 'a'..'z' -> percent (count x ws) (lowers ws)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.