N-grams: Difference between revisions

1,199 bytes added ,  2 months ago
→‎{{header|haskell}}: Added a Haskell version
(Realize in F#)
(→‎{{header|haskell}}: Added a Haskell version)
Line 336:
}
</pre>
 
=={{header|Haskell}}==
 
<syntaxhighlight lang=haskell>import Control.Applicative (ZipList (ZipList, getZipList))
import Data.Char (toUpper)
import Data.List (tails)
import qualified Data.Map.Strict as M
 
----------------- MAP OF N-GRAM COUNTS ----------------
 
nGramCounts :: Int -> String -> M.Map String Int
nGramCounts n s =
foldr
(flip (M.insertWith (+)) 1)
M.empty
(windows n s)
 
windows :: Int -> [a] -> [[a]]
windows n = getZipList . traverse ZipList . take n . tails
 
main :: IO ()
main =
let sample = toUpper <$> "Live and let live"
in mapM_
( \n ->
putStrLn (show n <> "-GRAMS:")
>> mapM_ print ((M.assocs . nGramCounts n) sample)
>> putStrLn ""
)
[2, 3, 4]</syntaxhighlight>
{{Out}}
<pre>2-GRAMS:
(" A",1)
(" L",2)
("AN",1)
("D ",1)
("E ",1)
("ET",1)
("IV",2)
("LE",1)
("LI",2)
("ND",1)
("T ",1)
("VE",2)
 
3-GRAMS:
(" AN",1)
(" LE",1)
(" LI",1)
("AND",1)
("D L",1)
("E A",1)
("ET ",1)
("IVE",2)
("LET",1)
("LIV",2)
("ND ",1)
("T L",1)
("VE ",1)
 
4-GRAMS:
(" AND",1)
(" LET",1)
(" LIV",1)
("AND ",1)
("D LE",1)
("E AN",1)
("ET L",1)
("IVE ",1)
("LET ",1)
("LIVE",2)
("ND L",1)
("T LI",1)
("VE A",1)</pre>
 
=={{header|jq}}==
9,655

edits