Advertisement
Guest User

f#

a guest
Apr 29th, 2017
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 1.82 KB | None | 0 0
  1. // Ex.1
  2.  
  3. let convertStringToWords s =
  4.     List.foldBack (fun c acc -> if c = ' ' then [] :: acc else [c :: acc.[0]] @ acc.[1..acc.Length-1]) [for ch in s -> ch] [[]]  
  5.    
  6. let printWordsToLines lineLength (ws:char list list) =
  7.     if ws |> List.map (fun w -> w.Length) |> List.max > lineLength then
  8.         failwith "Can not fit"
  9.     let rec wordsToLines (ws:char list list) offset =
  10.         match ws with
  11.         | [] -> []
  12.         | head::tail -> if head.Length + offset < lineLength
  13.                         then head @ [' '] @ wordsToLines tail (offset+head.Length+1)
  14.                         else ['\n'] @ head @ [' '] @ wordsToLines tail (head.Length+1)
  15.     wordsToLines ws 0
  16.  
  17. //Test
  18. convertStringToWords "Functional programming Fsharp" |> printWordsToLines 20
  19. (*Prints ['F'; 'u'; 'n'; 'c'; 't'; 'i'; 'o'; 'n'; 'a'; 'l'; ' '; '\010'; 'p'; 'r';
  20.    'o'; 'g'; 'r'; 'a'; 'm'; 'm'; 'i'; 'n'; 'g'; ' '; 'F'; 's'; 'h'; 'a'; 'r';
  21.    'p'; ' ']*)
  22.  
  23. convertStringToWords "Functional programming Fsharp" |> printWordsToLines 8
  24. //Shows an error - longest word is longer then 8
  25.  
  26.  
  27.  
  28. //Ex.2
  29.  
  30. let maximumWordsOnLine s =
  31.     let splitString s del =
  32.         List.foldBack (fun c acc -> if c = del then [] :: acc else [c :: acc.[0]] @ acc.[1..acc.Length-1]) [for ch in s -> ch] [[]]  
  33.     splitString s '\n' |> List.map (fun line -> (splitString line ' ').Length) |> List.max
  34.  
  35. //Test
  36. maximumWordsOnLine "one two three\none two three four\none\none two\none two three four five\none"
  37. //Returns 5
  38.  
  39.  
  40. //Ex.3
  41.  
  42. let countNumOfVowels s =
  43.      let countVovel v =
  44.         List.fold (fun acc c -> acc + (if List.contains c [v; System.Char.ToUpper v] then 1 else 0)) 0 [for ch in s -> ch]
  45.      (countVovel 'a', countVovel 'e', countVovel 'i', countVovel 'o', countVovel 'u')
  46.  
  47. //Test  
  48. countNumOfVowels "paradigm"
  49. //returns (2, 0, 1, 0, 0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement