简体   繁体   中英

Check if a word is in a list OCAML using fold

Suppose I want to extract a 4-letter word out of 6-letter word, say "hank" out of "thanks". Suppose there is also a list of 4-letter words that makes sense and I want to check that whether the 4-letter word I just extracted makes sense (ie if it shows up in the list of 4-letter words) and then I want to return a list of all 6-letter words from which extracted meaningful 4-letter words come. My thought is:

let is_4_init lst = 
    let acc = ([]) in
            let f (group) x =
                    let y = String.sub x 1 4 in
                    if List.mem y my_4words_list then ([x]) in
            let (final_group) = List.fold_left f acc lst in final_group

Error: This variant expression is expected to have type unit The constructor :: does not belong to type unit

why is this the case?

Thank you!

If you use if ... then without an else , then the type of the result must be unit . That's because the type needs to be the same for both cases. unit is the type of the value () , and is used when the result of an expression isn't particularly interesting.

Your function f should be returning an accumulated result, so it does return an interesting result. Returning unit is not what you want. You need to figure out what f should return when the test is false.

As a side comment, it's somewhat notable that you're not using the parameter named group anywhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM