views:

326

answers:

1

I'm trying to learn F# by translating some Haskell code I wrote a very long time ago, but I'm stuck!

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.

What is the name of the operation I am performing in freqs, and how do I translate it to F#?

Edit: count and lowers are Char -> String -> Int and String -> Int respectively, and I have translated these already.

Thanks

+9  A: 

This is a list comprehension, and in F# it looks like the last two lines below:

// 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
// [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)]
Brian
Thanks :) just what i needed
Andrew Bullock