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和lower分别是Char -> String -> Int和String -> Int,我已经翻译过了。
Thanks
谢谢
2 个解决方案
#1
13
This is a list comprehension, and in F# it looks like the last two lines below:
这是一个列表理解,在f#中它看起来像下面的最后两行:
// stub out since dunno 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)]
#2
0
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)]
#1
13
This is a list comprehension, and in F# it looks like the last two lines below:
这是一个列表理解,在f#中它看起来像下面的最后两行:
// stub out since dunno 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)]
#2
0
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)]