I am trying to think of a way of how to improve speed of my program and one of the parts is anagram generation. Would the async features help in this case or there is another technique of manipulating strings?
let anagramWords = [|"rolex";"viagra";"win";"free";"cash";"grand";"prize";
"nude";"porn";"casino";"lottery";"spins";"sex";"gold"; "buy"; "clearance";
"business"; "biz"; "money"; "opportunity"; "earn"; "extra"; "potential"; "sleep"; "discount";
"bargain"; "credit"; "affordable"; "loans"; "mortages"; "quote"; "dollars"; "invest"; "investment";
"bitcoin"; "silver"; "save"; "unsecured"; "pennies"; "million"; "billion";"bureaus";"stock";
"bankruptcy"; "eliminate"; "debt"; "billing"; "iphone"; "selling"; "obligation";"trial";
"vacation"; "winner";"membership"; "preview"; "sample"; "priority"; "website"; "gift"; "gifts";
"present"; "deal"; "fantastic"; "outstanding"; "values"; "act"; "lifetime"; "urgent"|]
let rec distribute e = function
| [] -> [[e]]
| x::xs' as xs -> (e::xs)::[for xs in distribute e xs' -> x::xs]
let rec permute = function
| [] -> [[]]
| e::xs -> List.collect (distribute e) (permute xs)
let genAnagrams word =
word
|>List.ofSeq
|>permute
|> List.map (fun x -> String(x |> Array.ofList))
|> Seq.ofList
|> Seq.toList
One very simple way to make this a bit faster is to make permute use arrays instead of lists and use Array.Parallel.collect instead of List.collect. Even with the inefficiency of taking the head off an array, it becomes about 30% faster for me for a word of 10 characters.
open System
let rec distribute e = function
| [] -> [[e]]
| x::xs' as xs -> (e::xs)::[for xs in distribute e xs' -> x::xs]
let arrayHeadTail = function [||] -> None | xs -> Some (xs.[0], Array.tail xs)
let rec permute xs =
match arrayHeadTail xs with
| None -> [| [] |]
| Some (e, xs) -> Array.Parallel.collect (distribute e >> List.toArray) (permute xs)
let genAnagrams word =
word
|> Seq.toArray
|> permute
|> Array.map String.Concat<char>
Related
I want to implement a generic recursion operator for (at first simple) ADTs.
(Simple means that only with constructors whose argument types are the defined one.) The general idea is to be able to use something as simple as $(recop ''Alg).
It is easy to write down the recursion operator manually for a given type.
data D = E | C D D
recD :: t -> ((D, t) -> (D, t) -> t) -> D -> t
recD rE rC = let r = recD rE rC in \case
E -> rE
C pC0 pC1 -> rC (pC0, r pC0) (pC1, r pC1)
I wanted to use templates for that. My problem is the recursive call e.g. r pC0. I got it working without the recursive call.
newNames :: String -> Int -> Q [Name]
newNames stem n = sequence [ newName (stem ++ show i) | i <- [1::Int .. n] ]
match' :: PatQ -> ExpQ -> MatchQ
match' pat exp = match pat (normalB exp) []
recop :: Name -> ExpQ
recop name = do
TyConI (DataD _ algName [] {-_-} ctors _) <- reify name
let ctorNames = [ ctorName | NormalC ctorName _ <- ctors ] :: [Name]
let ctorTypes = [ [ typ | (_, typ) <- bts ] | NormalC _ bts <- ctors ]
rs <- newNames ("r" ++ nameBase algName) (length ctorNames)
pss <- sequence [ newNames ("p" ++ nameBase algName ++ nameBase ctorName) (length ctorTypes) | (ctorName, ctorTypes) <- zip ctorNames ctorTypes ]
let pats = zipWith conP ctorNames (map varP <$> pss) :: [PatQ]
let prs = zipWith (\p r -> tupE [varE p, r]) ps "recursive calls"
lamE (varP <$> rs) $ lamCaseE [ match' pat $ foldl appE (varE r) prs | (r, pat, ps) <- zip3 rs pats pss ]
I don't know how to get the hole of "recursive calls" filled. I have no idea and suspect that it's not easily doable.
You do it exactly the same way you've done it in your concrete code; you generate let r = .. in .. and refer to that r to construct the recursive calls. Right now, you are just constructing the \case { .. } portion. Keep in mind you can rewrite recD as
recD =
let
recD_ = \rE rC ->
let r = recD_ rE rC
in ...
in recD_
Credit goes to user2407038 who answered the question in a comment.
The general pattern is to use an additional let construct:
recursive = let recursive_ = expression in recursive_
so you can refer to recursive_ in expression.
I have a big Excel file, which i read with Excel Provider in F#.
The rows should be grouped by some column. Processing crashes with OutOfMemoryException. Not sure whether the Seq.groupBy call is guilty or excel type provider.
To simplify it I use 3D Point here as a row.
type Point = { x : float; y: float; z: float; }
let points = seq {
for x in 1 .. 1000 do
for y in 1 .. 1000 do
for z in 1 .. 1000 ->
{x = float x; y = float y; z = float z}
}
let groups = points |> Seq.groupBy (fun point -> point.x)
The rows are already ordered by grouped column, e.g. 10 points with x = 10, then 20 points with x = 20 and so one. Instead of grouping them I need just to split the rows in chunks until changed. Is there some way to enumerate the sequence just once and get sequence of rows splitted, not grouped, by some column value or some f(row) value?
If the rows are already ordered then this chunkify function will return a seq<'a list>. Each list will contain all the points with the same x value.
let chunkify pred s = seq {
let values = ref []
for x in s do
match !values with
|h::t -> if pred h x then
values := x::!values
else
yield !values
values := [x]
|[] -> values := [x]
yield !values
}
let chunked = points |> chunkify (fun x y -> x.x = y.x)
Here chunked has a type of
seq<Point list>
Another solution, along the same lines as Kevin's
module Seq =
let chunkBy f src =
seq {
let chunk = ResizeArray()
let mutable key = Unchecked.defaultof<_>
for x in src do
let newKey = f x
if (chunk.Count <> 0) && (newKey <> key) then
yield chunk.ToArray()
chunk.Clear()
key <- newKey
chunk.Add(x)
}
// returns 2 arrays, each with 1000 elements
points |> Seq.chunkBy (fun pt -> pt.y) |> Seq.take 2
Here's a purely functional approach, which is surely slower, and much harder to understand.
module Seq =
let chunkByFold f src =
src
|> Seq.scan (fun (chunk, (key, carry)) x ->
let chunk = defaultArg carry chunk
let newKey = f x
if List.isEmpty chunk then [x], (newKey, None)
elif newKey = key then x :: chunk, (key, None)
else chunk, (newKey, Some([x]))) ([], (Unchecked.defaultof<_>, None))
|> Seq.filter (snd >> snd >> Option.isSome)
|> Seq.map fst
Lets start with the input
let count = 1000
type Point = { x : float; y: float; z: float; }
let points = seq {
for x in 1 .. count do
for y in 1 .. count do
for z in 1 .. count ->
{x = float x; y = float y; z = float z}
}
val count : int = 1000
type Point =
{x: float;
y: float;
z: float;}
val points : seq<Point>
If we try to evalute points then we get a OutOfMemoryException:
points |> Seq.toList
System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
at Microsoft.FSharp.Collections.FSharpList`1.Cons(T head, FSharpList`1 tail)
at Microsoft.FSharp.Collections.SeqModule.ToList[T](IEnumerable`1 source)
at <StartupCode$FSI_0011>.$FSI_0011.main#()
Stopped due to error
It might be same reason that groupBy fails, but I'm not sure. But it tells us that we have to use seq and yield to return the groups with. So we get this implementation:
let group groupBy points =
let mutable lst = [ ]
seq { for p in points do match lst with | [] -> lst <- [p] | p'::lst' when groupBy p' p -> lst <- p::lst | lst' -> lst <- [p]; yield lst' }
val group : groupBy:('a -> 'a -> bool) -> points:seq<'a> -> seq<'a list>
It is not the most easily read code. It takes each point from the points sequence and prepends it to an accumulator list while the groupBy function is satisfied. If the groupBy function is not satisfied then a new accumulator list is generated and the old one is yielded. Note that the order of the accumulator list is reversed.
Testing the function:
for g in group (fun p' p -> p'.x = p.x ) points do
printfn "%f %i" g.[0].x g.Length
Terminates nicely (after some time).
Other implementation with bug fix and better formatting.
let group (groupBy : 'a -> 'b when 'b : equality) points =
let mutable lst = []
seq {
yield! seq {
for p in points do
match lst with
| [] -> lst <- [ p ]
| p' :: lst' when (groupBy p') = (groupBy p) -> lst <- p :: lst
| lst' ->
lst <- [ p ]
yield (groupBy lst'.Head, lst')
}
yield (groupBy lst.Head, lst)
}
Seems there is no one line purely functional solution or already defined Seq method which I have overseen.
Therefore as an alternative here my own imperative solution. Comparable to #Kevin's answer but actually satisfies more my need. The ref cell contains:
The group key, which is calculated just once for each row
The current chunk list (could be seq to be conform to Seq.groupBy), which contains the elements in the input order for which the f(x) equals to the sored group key (requires equality).
.
let splitByChanged f xs =
let acc = ref (None,[])
seq {
for x in xs do
match !acc with
| None,_ ->
acc := Some (f x),[x]
| Some key, chunk when key = f x ->
acc := Some key, x::chunk
| Some key, chunk ->
let group = chunk |> Seq.toList |> List.rev
yield key, group
acc := Some (f x),[x]
match !acc with
| None,_ -> ()
| Some key,chunk ->
let group = chunk |> Seq.toList |> List.rev
yield key, group
}
points |> splitByChanged (fun point -> point.x)
The function has the following signature:
val splitByChanged :
f:('a -> 'b) -> xs:seq<'a> -> seq<'b * 'a list> when 'b : equality
Correctures and even better solutions are welcome
Help me translate following block of the Haskell code. The run function produces text string that corresponding to a given regex that abstracted as Pattern.
Declaration of the type Pattern you can see below in the block of F# code. You can test run function like
genex $ POr [PConcat [PEscape( DoPa 1) 'd'], PConcat [PEscape (DoPa 2) 'd']]
{-# LANGUAGE RecordWildCards, NamedFieldPuns #-}
import qualified Data.Text as T
import qualified Control.Monad.Stream as Stream
import Text.Regex.TDFA.Pattern
import Control.Monad.State
import Control.Applicative
genex = Stream.toList . run
maxRepeat :: Int
maxRepeat = 3
each = foldl1 (<|>) . map return
run :: Pattern -> Stream.Stream T.Text
run p = case p of
PBound low high p -> do
n <- each [low..maybe (low+maxRepeat) id high]
fmap T.concat . sequence $ replicate n (run p)
PConcat ps -> fmap T.concat . Stream.suspended . sequence $ map run ps
POr xs -> foldl1 mplus $ map run xs
PEscape {..} -> case getPatternChar of
'd' -> chars $ ['0'..'9']
'w' -> chars $ ['0'..'9'] ++ '_' : ['a'..'z'] ++ ['A'..'Z']
ch -> isChar ch
_ -> error $ show p
where
isChar = return . T.singleton
chars = each . map T.singleton
Below I give my poor attempt. It works but incorrectly. The problem is in the following.
Let assume parse produces Pattern like that
parse "\\d\\d";;
val it : Pattern = POr [PConcat [PEscape (DoPa 1,'d'); PEscape (DoPa 2,'d')]]
and
parse "\\d{2}";;
val it : Pattern = POr [PConcat [PBound (2,Some 2,PEscape (DoPa 1,'d'))]]
So feeding both patterns to run I expect to receive seq [['2'; '2']; ['2'; '3']; ['2'; '1']; ['2'; '4']; ...] that corresponding to seq ["22"; "23"; "21"; "24"; ...] (2 symbols per string)
This is valid in the first case,
POr [PConcat [PEscape (DoPa 1,'d'); PEscape (DoPa 2,'d')]] |> run;;
val it : seq = seq [['2'; '2']; ['2'; '3']; ['2'; '1']; ['2'; '4']; ...]
seq ["22"; "23"; "21"; "24"; ...]
but not in the second
POr [PConcat [PBound (2,Some 2,PEscape (DoPa 1,'d'))]] |> run;;
val it : seq = seq [['2']; ['2']; ['2']; ['3']; ...]
seq ["2"; "2", "2"; "3", "2"; "1", "2"; "4";...] (1 symbol per string)
I tested different variants with the following clauses:
| POr ps -> Seq.concat (List.map run ps)
| PConcat ps -> (sequence (List.map (run >> Seq.concat) ps))
| PBound (low,high,p) ->
but all in vain. I can't figure out the valid translation.
-Maybe I should use String or Array instead of char list.
-And I assume that Seq is quite good analogue to Control.Monad.Stream. Is it right?
Thanks in advance for help
open System
/// Used to track elements of the pattern that accept characters or are anchors
type DoPa = DoPa of int
/// Pattern is the type returned by the regular expression parser.
/// This is consumed by the CorePattern module and the tender leaves
/// are nibbled by the TNFA module.
type Pattern = PEmpty
| POr of Pattern list // flattened by starTrans
| PConcat of Pattern list // flattened by starTrans
| PBound of int * (int option) * Pattern // eliminated by starTrans
| PEscape of DoPa * char // Backslashed Character
let maxRepeat = 3
let maybe deflt f opt =
match opt with
| None -> deflt
| Some v -> f v
/// Cartesian production
/// try in F# interactive: sequence [[1;2];[3;4]];;
let rec sequence = function
| [] -> Seq.singleton []
| (l::ls) -> seq { for x in l do for xs in sequence ls do yield (x::xs) }
let from'space'to'tilda = [' '..'~'] |> List.ofSeq
let numbers = ['0'..'9'] |> List.ofSeq
let numbers'and'alphas = (['0'..'9'] # '_' :: ['a'..'z'] # ['A'..'Z']) |> List.ofSeq
let whites = ['\009'; '\010'; '\012'; '\013'; '\032' ] |> List.ofSeq
let rec run (p:Pattern) : seq<char list> =
let chars chs = seq { yield [for s in chs -> s] }
match p with
| POr ps -> Seq.concat (List.map run ps)
| PConcat ps -> (sequence (List.map (run >> Seq.concat) ps))
| PBound (low,high,p) ->
let ns = seq {low .. maybe (low + maxRepeat) id high}
Seq.concat (seq { for n in ns do yield sequence (List.replicate n (((run >> Seq.concat) p))) })
// Seq.concat (seq { for n in ns do yield ((List.replicate n (run p)) |> Seq.concat |> List.ofSeq |> sequence)})
//((List.replicate low (run p)) |> Seq.concat |> List.ofSeq |> sequence)
// PConcat [ for n in ns -> p] |> run
| PEscape(_, ch) ->
match ch with
| 'd' -> chars numbers
| 'w' -> chars numbers'and'alphas
| ch -> chars [ch]
| _ -> Seq.empty
I don't know why you didn't translate Data.Text from Haskell to string in F#, you just need to mimic two functions. Apart from that I did just a few changes to make it work, this way you can compare it easily with your original code, see replaced code between (* *)
open System
// Mimic Data.Text as T
module T =
let concat (x:seq<_>) = System.String.Concat x
let singleton (x:char) = string x
/// Used to track elements of the pattern that accept characters or are anchors
type DoPa = DoPa of int
/// Pattern is the type returned by the regular expression parser.
/// This is consumed by the CorePattern module and the tender leaves
/// are nibbled by the TNFA module.
type Pattern = PEmpty
| POr of Pattern list // flattened by starTrans
| PConcat of Pattern list // flattened by starTrans
| PBound of int * (int option) * Pattern // eliminated by starTrans
| PEscape of DoPa * char // Backslashed Character
let maxRepeat = 3
let maybe deflt f opt =
match opt with
| None -> deflt
| Some v -> f v
/// Cartesian production
/// try in F# interactive: sequence [[1;2];[3;4]];;
let rec sequence = function
| [] -> Seq.singleton []
| (l::ls) -> seq { for x in l do for xs in sequence ls do yield (x::xs) }
let from'space'to'tilda = [' '..'~'] |> List.ofSeq
let numbers = ['0'..'9'] |> List.ofSeq
let numbers'and'alphas = (['0'..'9'] # '_' :: ['a'..'z'] # ['A'..'Z']) |> List.ofSeq
let whites = ['\009'; '\010'; '\012'; '\013'; '\032' ] |> List.ofSeq
let rec run (p:Pattern) (*: seq<char list> *) =
(* let chars chs = seq { yield [for s in chs -> s] } *)
let chars (chs:seq<char>) = Seq.map string chs
match p with
| POr ps -> Seq.concat (List.map run ps)
| PConcat ps -> Seq.map T.concat << sequence <| List.map run ps (* (sequence (List.map (run >> Seq.concat) ps)) *)
| PBound (low,high,p) ->
seq {
for n in [low..maybe (low+maxRepeat) id high] do
yield! ( (Seq.map T.concat << sequence) (List.replicate n (run p)) )}
(*let ns = seq {low .. maybe (low + maxRepeat) id high}
Seq.concat (seq { for n in ns do yield sequence (List.replicate n (((run >> Seq.concat) p))) *)
// Seq.concat (seq { for n in ns do yield ((List.replicate n (run p)) |> Seq.concat |> List.ofSeq |> sequence)})
//((List.replicate low (run p)) |> Seq.concat |> List.ofSeq |> sequence)
// PConcat [ for n in ns -> p] |> run
| PEscape(_, ch) ->
match ch with
| 'd' -> chars numbers
| 'w' -> chars numbers'and'alphas
| ch -> chars [ch]
| _ -> Seq.empty
UPDATE
If you are translating Haskell code to F# you may try using this code which mimics many Haskell functions, including those using Type Classes.
I did a test translating as close as possible to your original Haskell code but using F# List (not lazy) and looks like this:
#load "Prelude.fs"
#load "Monad.fs"
#load "Applicative.fs"
#load "Monoid.fs"
open Prelude
open Control.Monad.Base
open Control.Applicative
module T =
let concat (x:list<_>) = System.String.Concat x
let singleton (x:char) = string x
type DoPa = DoPa of int
type Pattern = PEmpty
| POr of Pattern list
| PConcat of Pattern list
| PBound of int * (int option) * Pattern
| PEscape of DoPa * char
let maxRepeat = 3
let inline each x = foldl1 (<|>) << map return' <| x
let rec run p:list<_> =
let inline isChar x = return' << T.singleton <| x
let inline chars x = each << map T.singleton <| x
match p with
| PBound (low,high,p) -> do' {
let! n = each [low..maybe (low+maxRepeat) id high]
return! (fmap T.concat << sequence <| replicate n (run p))}
| PConcat ps -> fmap T.concat << sequence <| map run ps
| POr xs -> foldl1 mplus <| map run xs
| PEscape (_, ch) ->
match ch with
| 'd' -> chars <| ['0'..'9']
| 'w' -> chars <| ['0'..'9'] # '_' :: ['a'..'z'] # ['A'..'Z']
| ch -> isChar ch
| _ -> failwith <| string p
let genex = run
I am trying to format text to be in the shape of a rectangle; currently I have been able to get it properly left justified, but the last line does not extend as far as possible.
I am trying to calculate the optimum field width in order to minimise or remove this entirely.
I am totally stuck. The code below shows the relevant functions. At the moment it gets stuck in an infinite loop.
Where am I going wrong?
On a side note, what is the best way of debugging Haskell code?
(Yes, I'm very new to this.)
optimumFieldWidth is supposed to compare line lengths until the length of the top line is equal to that of the bottom line, then return the field width which causes this to be true.
module Main where
import System
import Data.List
main = do
(f:_) <- getArgs
xs <- getContents
putStr (show (bestFieldWidth maxLineLength xs))
bestFieldWidth :: Int -> String -> Int
bestFiledWidth _ [] = 0
bestFieldWidth lineLength xs
| length (last input) == length (head input) = lineLength
| otherwise = bestFieldWidth (length (head (rect (lineLength-1) xs))) xs
where input = lines xs
rect :: Int -> String -> [String]
rect _ [] = []
rect lineLength xs
| length input <= len = [input]
| otherwise = take len input : rect len (drop len input)
where input = trim xs
len = bestFieldWidth lineLength xs
maxLineLength :: Int
maxLineLength = 40
All responses are appreciated. Thank you.
I thought I'd put the actual solution here in case any other nutters wish to do this.
Please bear in mind that it was written by a moron so it probably isn't the most elegant solution.
maxFieldWidth :: Int
maxFieldWidth = 30
rect :: String -> String
rect xs = (unlines (chunk (bestFieldWidth (maxFieldWidth) (lines input)) input))
where input = itemsReplace '\n' ' ' xs
--Should be called with the point maximum desired width as n
bestFieldWidth :: Int -> [String] -> Int
bestFieldWidth _ [] = error "bestFieldWidth: Empty List"
bestFieldWidth n xs
| n == 6 = 6
| 1 == (length (last input)) = n
| otherwise = (bestFieldWidth (n-1) xs)
where input = chunk n (unlines xs)
chunk :: Int -> [a] -> [[a]]
chunk n [] = []
chunk n xs = ys : chunk n zs
where (ys,zs) = splitAt n xs
itemsReplace :: Eq a => a -> a -> [a] -> [a]
itemsReplace _ _ [] = []
itemsReplace c r (x:xs)
| c == x = r:itemsReplace c r xs
| otherwise = x:itemsReplace c r xs
It seems that the condition length (last input) == length (head input) once false never goes true in subsequent calls to area, thus making this function always take the otherwise branch and keep calling itself indefinitely with the same values of xs and thus input.
Possible cause of this is that you use the lines function, which splits a string with newline characters, in a way not dependent on lineLength and inconsistent with your line-splitting in the rect function.
In answer to your side note, here is an excellent guide to debugging Haskell: http://cgi.cse.unsw.edu.au/~dons/blog/2007/11/14
There's also Debug.Trace, which allows you to insert print statements. It should of course only be used while debugging, because it makes your function have side effects.
http://hackage.haskell.org/packages/archive/base/latest/doc/html/Debug-Trace.html
In F# I want to transform a list of chars into a string. Consider the following code:
let lChars = ['a';'b';'c']
If I simply do lChars.ToString, I get "['a';'b';'c']". I'm trying to get "abc". I realize I could probably do a List.reduce to get the effect I'm looking for but it seems like there should be some primitive built into the library to do this.
To give a little context to this, I'm doing some manipulation on individual characters in a string and when I'm done, I want to display the resulting string.
I've tried googling this and no joy that way. Do I need to just bite the bullet and build a List.reduce expression to do this transformation or is there some more elegant way to do this?
Have you tried
System.String.Concat(Array.ofList(lChars))
How many ways can you build a string in F#?
Here's another handful:
let chars = ['H';'e';'l';'l';'o';',';' ';'w';'o';'r';'l';'d';'!']
//Using an array builder
let hw1 = new string [|for c in chars -> c|]
//StringBuilder-Lisp-like approach
open System.Text
let hw2 =
string (List.fold (fun (sb:StringBuilder) (c:char) -> sb.Append(c))
(new StringBuilder())
chars)
//Continuation passing style
let hw3 =
let rec aux L k =
match L with
| [] -> k ""
| h::t -> aux t (fun rest -> k (string h + rest) )
aux chars id
Edit: timings may be interesting? I turned hw1..3 into functions and fed them a list of 500000 random characters:
hw1: 51ms
hw2: 16ms
hw3: er... long enough to grow a beard? I think it just ate all of my memory.
Didn't see this one here, so:
let stringFromCharList (cl : char list) =
String.concat "" <| List.map string cl
"" is just an empty string.
FSI output:
> stringFromCharList ['a'..'d'];;
val it : string = "abcd"
EDIT:
Didn't like this syntax coming back to this so here's a more canonically functional one:
['a'..'z'] |> List.map string |> List.reduce (+)
['a';'b';'c'] |> List.fold_left (fun acc c -> acc ^ (string c)) ""
Edited:
Here is yet another funny way to do your task:
type t =
| N
| S of string
static member Zero
with get() = N
static member (+) (a: t, b: t) =
match a,b with
| S a, S b -> S (a+b)
| N, _ -> b
| _, N -> a
let string_of_t = function
|N -> ""
|S s -> s
let t_of_char c = S (string c)
['a'; 'b'; 'c'] |> List.map t_of_char |> List.sum |> string_of_t
Sadly, just extending System.String with 'Zero' member does not allow to use List.sum with strings.
Edited (answer to Juilet):
Yes, you are right, left fold is slow. But i know more slow right fold :) :
#r "FSharp.PowerPack"
List.fold_right (String.make 1 >> (^)) ['a';'b';'c'] ""
and of course there is fast and simple:
new System.String(List.to_array ['1';'2';'3'])
And i used 'sprintf' seems to me easier:
let t = "Not what you might expect"
let r = [ for i in "aeiou" -> i]
let q = [for a in t do if not (List.exists (fun x -> x=a) r) then yield a]
let rec m = function [] -> "" | h::t -> (sprintf "%c" h) + (m t)
printfn "%A" (m q)
The following solution works for me:
let charList = ["H";"E";"L";"L";"O"]
let rec buildString list =
match list with
| [] -> ""
| head::tail -> head + (buildString tail)
let resultBuildString = buildString charList
[|'w'; 'i'; 'l'; 'l'|]
|> Array.map string
|> Array.reduce (+)
or as someone else posted:
System.String.Concat([|'w'; 'i'; 'l'; 'l'|])